NgIf 指令作用
ngIf 指令用于根据表达式的值,在指定位置渲染 then 或 else 模板的内容。
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 抽象类的定义如下:
// angular/packages/core/src/linker/template_ref.tsexport abstract class TemplateRef<C> { abstract get elementRef(): ElementRef; abstract createEmbeddedView(context: C): EmbeddedViewRef<C>;}
ViewContainerRef
ViewContainerRef 实例提供了 createEmbeddedView()
方法,该方法接收 TemplateRef
对象作为参数,并将模板中的内容作为容器 (comment 元素) 的兄弟元素,插入到页面中。
NgIfContext
NgIfContext 实例用于表示 NgIf 上下文。
// angular/packages/common/src/directives/ng_if.tsexport class NgIfContext { public $implicit: any = null; public ngIf: any = null;}
新闻热点
疑难解答
图片精选