Angular 4.x NgIf

2017-10-16  本文已影响0人  h266094

ngIf 指令用于根据表达式的值,在指定位置渲染 then 或 else 模板的内容。

使用ngIf

此时判断表达式的布尔值,控制元素的显影

<!--语法糖-->
<div *ngIf="condition">...</div>
<!--Angular 2.x中使用template-->
<ng-template [ngIf]="condition"><div>...</div></ng-template>

使用else块

此时如果condition的值为true时,显示当前元素的内容,否则显示elseBlock模版。

<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>

使用then和else块

此时如果condition的值为true时,显示thenBlokc模版的内容,否则显示elseBlock模版。

<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>

NgIf 使用示例

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toggleFlag1= true;
  toggleFlag2= true;
  toggleFlag3= true;
  
  onToggle1() {
      this.toggleFlag1 = (this.toggleFlag1 === true)? false : true;
  }
  onToggle2() {
      this.toggleFlag2 = (this.toggleFlag2 === true)? false : true;
  }
  onToggle3() {
      this.toggleFlag3 = (this.toggleFlag3 === true)? false : true;
  }  

}

app.component.html

<h3>ng-template with ngIf</h3>
<button type="button" (click)="onToggle1()">Toggle</button>

<ng-template [ngIf]= "toggleFlag1" >
   <div>Hello World!</div>
</ng-template>

<h3>ng-template with ngIf-else</h3>

<button type="button" (click)="onToggle2()">Toggle</button>

<div *ngIf="toggleFlag2; else msgElseBlock" >
   <div>Hello World!</div>
</div>

<ng-template #msgElseBlock>
   <div>Else Block: Hello World! </div>
</ng-template>

<h3>ng-template with ngIf-then-else</h3>

<button type="button" (click)="onToggle3()">Toggle</button>

<div *ngIf="toggleFlag3; then thenBlock else elseBlock">

</div>
<ng-template #thenBlock>
    <div>Then Block: Hello World!</div>
</ng-template>
<ng-template #elseBlock>
    <div>Else Block: Hello World!</div>
</ng-template> 
上一篇下一篇

猜你喜欢

热点阅读