详解详解Angular 4.x NgIf 的用法的用法
本篇文章主要介绍了详解Angular 4.x NgIf,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟
随小编过来看看吧
NgIf 指令作用指令作用
ngIf 指令用于根据表达式的值,在指定位置渲染 then 或 else 模板的内容。
1. then 模板除非绑定到不同的值,否则默认是 ngIf 指令关联的内联模板。
2. else 模板除非绑定对应的值,否则默认是 null。
NgIf 指令语法指令语法
简单形式
<!--语法糖-->
<div *ngIf="condition">...</div>
<!--Angular 2.x中使用template-->
<ng-template [ngIf]="condition"><div>...</div></ng-template>
使用else块
<div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>
使用then和else块
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>
使用as语法
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>
NgIf 使用示例使用示例
@Component({
selector: 'ng-if-then-else',
template: `
<button (click)="show = !show">{{show ? 'hide' : 'show'}}</button>
<button (click)="switchPrimary()">Switch Primary</button>
show = {{show}}
<br>
<div *ngIf="show; then thenBlock; else elseBlock">this is ignored</div>
<ng-template #primaryBlock>Primary text to show</ng-template>
<ng-template #secondaryBlock>Secondary text to show</ng-template>
<ng-template #elseBlock>Alternate text while primary text is hidden</ng-template>
`
})
class NgIfThenElse implements OnInit {
thenBlock: TemplateRef<any> = null;
show: boolean = true;
@ViewChild('primaryBlock')
primaryBlock: TemplateRef<any> = null;
@ViewChild('secondaryBlock')
secondaryBlock: TemplateRef<any> = null;
switchPrimary() {
this.thenBlock = this.thenBlock === this.primaryBlock ?
this.secondaryBlock : this.primaryBlock;
}
ngOnInit() {
this.thenBlock = this.primaryBlock;
}
}
基础知识基础知识
TemplateRef
TemplateRef 实例用于表示模板对象,TemplateRef 抽象类的定义如下: