学习怎麽使用 Angular 的 *ngIf
语法。
让你可以有条件地去选择要不要渲染某些内容在画面上。
ngIf 有以下三种属性
ngIf
: 在 ngIf 会接一个判断条件,这个判断条件会回传布林值,以此来决定是否要渲染指定的内容。
ngIfThen
: 如果判断条件是 true,就会将 ngIfThen
指定的内容渲染到画面上。
ngIfElse
: 如果判断条件是 false,就会将 ngIfElse
指定的内容渲染到画面上。
我们直接把 *ngIf="condition"
写在要被判断的元素的 html 标签上。
--- app.component.html ---
<div *ngIf="renderCondition">Content to render when condition is true.</div>
<button (click)="renderCondition != renderCondition">Switch</button>
-- app.component.ts --
export class AppComponent {
renderCondition = false;
}
以上的范例,透过按下按钮来切换 renderCondition 的布林值,以此决定是否 div 要不要被渲染到画面上。
我们可以加入 ng-template
来负责渲染当判断式为 false 的内容。
--- app.component.html ---
<div *ngIf="renderCondition; else elseContent">condition is true</div>
<ng-template #elseContent>
<div>condition is false</div>
</ng-template>
<button (click)="renderCondition = !renderCondition">switch</button>
--- app.component.ts ---
export class AppComponent {
renderCondition = false;
}
以上的范例,我们先用了 #elseContent 来取得目标元素内容。
接着,在 ngIf 判断式里面我们还有加上了 else 的内容,*ngIf="renderCondition; else elseContent"
,这个判断式的内容就是当 renderCondition 为 true 就呈现它所在元素的内容,若为 false,就呈现 elseContent 指定的内容。
除了将 else 加入判断式里面,我们再加入 then 到判断式中。
--- app.component.html ---
<div *ngIf="renderCondition; then thenContent; else elseContent"></div>
<ng-template #thenContent>
<div>condition is true</div>
</ng-template>
<ng-template #elseContent>
<div>condition is false</div>
</ng-template>
<button (click)="renderCondition = !renderCondition">switch</button>
--- app.component.ts ---
export class AppComponent {
renderCondition = false;
}
以上的范例,还额外用了 thenContent 来取得指定元素,用以渲染当判断式为 true 时的内容。
在实际的产品中,我们很常会需要非同步的去取得资料,那当资料还没回传的时候,该资料会是 undefined 的状态,这会导致浏览器报错,那这个时候,我们就可以用 ngIf 来判断当要被渲染到画面上的资料为 undefined 的时候,呈现其他的内容,例如: 等待画面。
@Component({
selector: 'ng-if-as',
template: `
<button (click)="nextUser()">Next User</button>
<br>
<div *ngIf="getUserInfo; else loading">
<p *ngFor="let user of userInfo">
{{ user.name }}
</p>
</div>
<ng-template #loading >Waiting...</ng-template>
`
})
export class NgIfAs {
userInfo = []
getUserInfo() {
// 非同步取得 userInfo 资料
}
ngOnInit () {
this.getUserInfo()
}
}
以上这个范例,就是会先去非同步取得使用者的资料,并利用 ngIf 先去判断是否 userInfo 有资料,若没有就先呈现 loading 的画面。
这边做个总结
<<: LiteX/VexRiscv 简介与使用 (二) 始有昼夜
>>: [Day16] 学 Reactstrap 就离 React 不远了 ~ 用 Tooltips 认识 useEffect
要将YouTube影片下载爲MP4格式,您必须首先找到YouTube影片的地址。您可以复制地址并将其...
在过去撰写的程序都是以单页的形式呈现, 但实际上架的APP多不只一页, 那要如何从A页跳至B页? 这...
嘿嘿~结果还没进入渗透测试篇XD 决定先来个作业系统相关的Linux篇。 从事资安的行业,需要对Li...
系统名称:小白的食谱搜寻系统 题目选择原因 其实icebear是一个患有重度选择困难症的人,常常会为...
在引用资料来源的时候,除了上传csv的选项,另外一个就是BigQuery。 早在开始摸索ML之前,G...