国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解Angular 4.x NgIf 的用法

2024-05-06 15:16:56
字體:
供稿:網(wǎng)友

NgIf 指令作用

ngIf 指令用于根據(jù)表達式的值,在指定位置渲染 then 或 else 模板的內(nèi)容。

    then 模板除非綁定到不同的值,否則默認是 ngIf 指令關(guān)聯(lián)的內(nèi)聯(lián)模板。 else 模板除非綁定對應(yīng)的值,否則默認是 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; }}

基礎(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;}            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 惠东县| 鹿邑县| 会宁县| 洛隆县| 万载县| 旌德县| 通许县| 闽清县| 高雄县| 汨罗市| 元氏县| 罗田县| 东乡| 平武县| 隆化县| 大新县| 建阳市| 安阳县| 屏东市| 皋兰县| 洛隆县| 公主岭市| 福建省| 安龙县| 绥江县| 隆安县| 衢州市| 武乡县| 遂宁市| 皋兰县| 峨山| 濮阳县| 西丰县| 贡山| 雷山县| 平塘县| 英德市| 德庆县| 宁晋县| 锡林郭勒盟| 越西县|