条件¶
在angular中,按条件显示会用到ngIf
首先在组件的类中定义一个名为messages的变量,类型是string[],
然后定义一个名为contents的变量,类型也是string[]
app.component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 | import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'SampleApp'; messages: string[] = ["message1","message2","message3"]; contents: string[] = ["contents1","contents2"]; } |
然后在对应的html文件app.component.html写入:
app.component.html:
1 2 3 4 5 6 7 8 9 10 | <div *ngIf="messages.length >= 3"> <div *ngFor="let message of messages"> <span>{{ message }}</span> </div> </div> <div *ngIf="contents.length >= 3"> <div *ngFor="let content of contents"> <span>{{ content }}</span> </div> </div> |
意思是当messages或者contents的个数大于3时,显示div本身,并循环显示数组中的数据
要注意ngIf和ngFor不能写在同一个标签中,所以这里必须写两层
ngIf后的条件可以是任意的布尔表达式
- ngIf也需要带上前面的“*”
效果如下:

如果将contents的数据修改为以下结果:
1 | contents: string[] = ["contents1","contents2","aaaa"]; |
刷新画面显示如下:

表示ngIf的确运行了
switch条件¶
除了if,还可以用switch来进行条件处理
首先在类中写入:
app.component.ts:
1 2 3 4 5 6 7 8 9 10 | import { Component, OnInit, OnChanges } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ status: string[] = ["1", "2", "3", "", "1"]; } |
然后在html中写入:
app.component.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <div *ngFor="let st of status"> <span [ngSwitch]="st"> <p *ngSwitchCase="1"> 早上好 </p> <p *ngSwitchCase="2"> 中午好 </p> <p *ngSwitchCase="3"> 晚上好 </p> <p *ngSwitchDefault> ... </p> </span> </div> |
switch包含三个指令:ngSwitch,ngSwitchCase,ngSwitchDefault
ngSwitch相当于switch关键字
ngSwitchCase相当于case关键字
ngSwitchDefault相当于default关键字
其中ngSwitchCase和ngSwitchDefault需要添加“*”符号
这个html中循环了status数组,然后根据分支显示了不同的结果:
