记录生活中的点滴,分享、学习、创新
Angular 中常用的指令有用来遍历的 *ngFor 、控制元素显示隐藏的 *ngIf,今天学习一下 *ngIf 这个常用的指令。
ngIf 指令用于根据表达式的值,在指定位置渲染then 或 else 模板的内容。then 模板除非绑定到不同的值,否则默认是 ngIf 指- 令关联的内联模板。else 模板除非绑定对应的值,否则默认是 null。
简单形式
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> | 
在我们的实际业务中可能遇到这样的需求,一个 table 表格,最后一列有修改、删除或者其他操作,当我们点击修改按钮的时候,当前这一行的内容都出现在一个 input 输入框里面,然后我们可以直接进行修改,这个时候我们就可以使用 *ngIf 和 else 来实现。效果图如下:


部分实现代码:
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 可以理解为一个模板 id ,它指向 <ng-template #inputid> 这个模板,当 item.bol 为 false 时,angular就会找到这个模板里的内容进行替换。
注意这个模板 id 是唯一的,如果多次使用 *ngIf else 指令需要使用不同的 id。
到此这篇关于angular *Ngif else用法详解的文章就介绍到这了,更多相关angular *Ngif else内容请搜索脚本之家以前的文章