ngIf 是一个指令,用于隐藏和显示DOM树中的HTML元素。它的作用就像java或javascript等编程语言中的if条件表达。这篇文章讲述了以下内容
- Angular中的ngIf标准指令
- 在Angular中使用ngif then else模板
- 逻辑和比较运算符的使用
- NgIf async Observable示例
- ngIf的空值检查用法
- ngIf模板中的常见错误
Angular ngIf指令
ngIf CommonModule 是一个来自 包中声明的指令。@angular/common
ngIf接受的表达式评估为真或假。如果它是真的,添加一个元素到DOM树,如果是假的,元素从DOM树中删除。
语法
<element *ngIf=(conditionalexpression) />
同样可以使用模板语法来重写
<ng-template [ngIf]="expression">
</ng-template>
element是有效的angular自定义元素或html元素。例子有p,div,span等...
*ngIf是应用于元素的关键字。
条件表达式是使用同步或异步调用的JavaScript表达式总是被评估为布尔值。
ngIf的基本例子
这是一个简单的变量,声明为真,内容就会显示给用户。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
bool:Boolean=true;
}
在html模板中
<div *ngIf="bool">
Show the element
</div>
ngIf表达式示例
该表达式可以包含使用以下运算符的JavaScript表达式
- 逻辑运算符(&&,||或!)。
- 比较运算符
逻辑运算符示例逻辑运算符用于在一个表达式中应用多个条件
在下面的例子中,如果角色是管理员或超级管理员,就会显示编辑个人资料的按钮Logical or (||) 如果其中一个表达式为真,则评估为真Logical And (&&) 如果所有条件表达式评估为真,则评估为真Logical Not (|) 如果条件表达式评估为假,则评估为真
<button *ngIf="role === 'admin' || role ==='superadmin'" >Edit profile</button>
<button *ngIf="role !== 'admin' && role ==='superadmin' && role!=='user'" >Login</button>
比较运算符的例子以下是一个检查角色类型的例子
role是一个在typecript组件中声明的变量,如下所示
let role:string;
和=== 和== 操作符被用来比较字符串并返回布尔值。
Angular if then else模板
这是一个在html模板中实现类似if else条件块操作的例子。表达式被评估为布尔值,如果为真,则块被添加,否则块被添加到DOM中。请注意,模板变量在ng-template 中被声明和引用,以动态加载。** 语法**
上述同样的语法可以用if else then directive ,改写如下
<div *ngIf="expression; then thenTemplate else elseTemplate"></div>
<ng-template #thenTemplate>This is shown when expression is true.</ng-template>
<ng-template #elseTemplate>This is shown when expression is false.</ng-template>
例子如果角色是管理员,Admintemplate被加载到DOM树中,否则usertemplate被添加到DOM树中
<div *ngIf="role==='admin'; then AdminTemplate else UserTemplate">
</div>
<ng-template #AdminTemplate>
Admin Dashboard
</ng-template>
<ng-template #UserTemplate>
User Dashboard
</ng-template>
ngIf async observable的用法
有些时候我们想检查异步值,这意味着当表单以默认值加载时,一旦异步调用完成,表达式就会随着时间的推移以新值更新。
为了使其成为条件表达式,在表达式中添加带有async关键字的管道。
<div *ngfor="let user of users$ | async" *ngIf="(isLoaded$ | async)">display user data</div>
在下面的代码中,isLoaded的初始值是false,这将不会分散用户数据,一旦API调用返回可观察的用户数据。在成功回调中使用成功和错误回调订阅可观察数据,isLoaded被更新为true。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public isLoaded: boolean = false;
users: any[];
ngOnInit() {
this.getAPIData();
}
private getAPIData() {
this.APIService.getDatabaseRows().subscribe(
(response) => {
if (response ) {
this.isLoaded = true;
this.users=response;
}
},
(error) => {
console.log(error);
this.users=null;
}
);
}
}
Angular ngIf null检查示例
html模板中的null检查可以在对象中没有数据时不加载组件。例如,emailList是一个对象的数组,要检查一个空或列表是空的。
在typescript中,emailList变量持有数组的数据,可以从API中获取。
let emailList: any[];
<div *ngIf="!emailList || emailList.length === 0">
<p>Inbox is empty</p>
</div>
Angular中没有TemplateRef的提供者
ngIf指令应用于html div元素,在typescript组件中初始化了bool值,显示的内容被输出到浏览器。
请注意,ngIf的前缀是* ,如果忽略了* ,下面的代码就会出现错误,如果*没有前缀的话
<div ngIf="bool"> show </div>
就会出现错误 -NullInjectorError 。没有TemplateRef的提供者!
不能绑定到'ngIf',因为它不是'div'的已知属性。
ngIf是angular指令,你不会在你的应用程序中自动使用。
要使用指令,需要在你的应用程序中导入CommonModule。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
@NgModule({
imports: [ CommonModule ],
declarations: [ ],
bootstrap: [ ]
})
export class AppModule { }
表达式被检查后发生了变化
这是一个问题,当条件表达式评估与Observable asyn调用,但模板使用条件表达式没有async管道符号。
在ngIf指令中对条件表达式使用async管道
<div *ngIf="{variable$|async}">content</div>