angular *Ngif else用法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

angular *Ngif else用法详解

陈仙生   2020-12-15 我要评论
这篇文章主要介绍了angular *Ngif else用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

Angular 中常用的指令有用来遍历的 *ngFor 、控制元素显示隐藏的 *ngIf,今天学习一下 *ngIf 这个常用的指令。

NgIf 指令

ngIf 指令用于根据表达式的值,在指定位置渲染then 或 else 模板的内容。
then 模板除非绑定到不同的值,否则默认是 ngIf 指- 令关联的内联模板。
else 模板除非绑定对应的值,否则默认是 null。

简单形式

<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>

在我们的实际业务中可能遇到这样的需求,一个 table 表格,最后一列有修改、删除或者其他操作,当我们点击修改按钮的时候,当前这一行的内容都出现在一个 input 输入框里面,然后我们可以直接进行修改,这个时候我们就可以使用 *ngIfelse 来实现。效果图如下:

在这里插入图片描述

在这里插入图片描述

部分实现代码:

<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.bolfalse 时,angular就会找到这个模板里的内容进行替换。

注意这个模板 id 是唯一的,如果多次使用 *ngIf else 指令需要使用不同的 id。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们