Angular 10 NgIf指令
在这篇文章中,我们将看到Angular 10中的NgIf是什么以及如何使用它。
Angular10中的ngIf指令是用来根据表达式移除或重新创建部分HTML元素的。如果它里面的表达式是假的,那么该元素就被移除,如果是真的,那么该元素就被添加到DOM中。
语法:
<li *ngIf='condition'></li>
NgModule:NgIf使用的模块是。
- CommonModule
Selectors:
- [ngIf]
步骤:
- 创建一个要用的Angular应用程序。
- 使用NgIf不需要任何导入。
- 在app.component.ts中用ngIf指令定义要检查的条件的变量。
- 在app.component.html中使用带有条件的NgIf指令进行检查。
- 使用ng serve为angular应用程序提供服务,以查看输出。
示例 1:
import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformWorkerApp } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
myBool = true;
}
<div *ngIf = 'myBool'>Boolean is set to true</div>
输出:
示例 2:
import { Component, Inject } from '@angular/core';
import { PLATFORM_ID } from '@angular/core';
import { isPlatformWorkerApp } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
variab = 10;
}
<div *ngIf = 'variab==1; else multi'>{{variab}}</div>
<ng-template #multi>
{{variab *2}}
</ng-template>
输出: