NgIf 指令作用
ngIf 指令用于根據(jù)表達式的值,在指定位置渲染 then 或 else 模板的內(nèi)容。
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; }}基礎(chǔ)知識
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 對象作為參數(shù),并將模板中的內(nèi)容作為容器 (comment 元素) 的兄弟元素,插入到頁面中。
NgIfContext
NgIfContext 實例用于表示 NgIf 上下文。
// angular/packages/common/src/directives/ng_if.tsexport class NgIfContext { public $implicit: any = null; public ngIf: any = null;}
新聞熱點
疑難解答
圖片精選