Angular 中常用的指令有用來(lái)遍歷的 *ngFor
、控制元素顯示隱藏的 *ngIf
,今天學(xué)習(xí)一下 *ngIf
這個(gè)常用的指令。
NgIf 指令
ngIf 指令用于根據(jù)表達(dá)式的值,在指定位置渲染then 或 else 模板的內(nèi)容。
then 模板除非綁定到不同的值,否則默認(rèn)是 ngIf 指- 令關(guān)聯(lián)的內(nèi)聯(lián)模板。
else 模板除非綁定對(duì)應(yīng)的值,否則默認(rèn)是 null。
簡(jiǎn)單形式
1
2
3
|
<div *ngIf= "condition" >...</div> <!--Angular 2.x中使用template--> <ng-template [ngIf]= "condition" ><div>...</div></ng-template> |
else
1
2
|
<div *ngIf= "condition; else elseBlock" >...</div> <ng-template #elseBlock>...</ng-template> |
then 和 else
1
2
3
|
<div *ngIf= "condition; then thenBlock else elseBlock" ></div> <ng-template #thenBlock>...</ng-template> <ng-template #elseBlock>...</ng-template> |
在我們的實(shí)際業(yè)務(wù)中可能遇到這樣的需求,一個(gè) table
表格,最后一列有修改、刪除或者其他操作,當(dāng)我們點(diǎn)擊修改按鈕的時(shí)候,當(dāng)前這一行的內(nèi)容都出現(xiàn)在一個(gè) input
輸入框里面,然后我們可以直接進(jìn)行修改,這個(gè)時(shí)候我們就可以使用 *ngIf
和 else
來(lái)實(shí)現(xiàn)。效果圖如下:
部分實(shí)現(xiàn)代碼:
1
2
3
4
5
6
7
|
<tr *ngFor= "let item of gridList" > <td *ngIf= "item.bol; else inputid" >{{item.id}}</td> <ng-template #inputid> <td class= "insert" ><input type= "text" [value]= "item.id" ></td> </ng-template> ... </tr> |
這里的 inputid
可以理解為一個(gè)模板 id
,它指向 <ng-template #inputid>
這個(gè)模板,當(dāng) item.bol
為 false
時(shí),angular就會(huì)找到這個(gè)模板里的內(nèi)容進(jìn)行替換。
注意這個(gè)模板 id 是唯一的,如果多次使用 *ngIf else
指令需要使用不同的 id。
到此這篇關(guān)于angular *Ngif else用法詳解的文章就介紹到這了,更多相關(guān)angular *Ngif else內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_45745643/article/details/111147834