Angular 10 NgIf 指令
在本文中,我们将了解 Angular 10 中的NgIf是什么以及如何使用它。
Angular10 中的ngIf 指令用于根据表达式删除或重新创建 HTML 元素的一部分。如果其中的表达式为假,则删除元素,如果为真,则将元素添加到 DOM。
句法:
NgModule:NgIf使用的模块是:
- 通用模块
选择器:
- [ngIf]
方法:
- 创建一个要使用的 Angular 应用程序。
- 使用NgIf不需要任何导入。
- 在 app.component.ts 中定义要使用ngIf指令检查其条件的变量。
- 在 app.component.html 中使用带有要检查条件的 NgIf 指令。
- 使用 ng serve 为 Angular 应用程序提供服务以查看输出。
示例 1:
app.component.ts
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;
}
app.component.html
Boolean is set to true
Javascript
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;
}
app.component.html
{{variab}}
{{variab *2}}
app.component.html
Boolean is set to true
输出:
示例 2:
Javascript
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;
}
app.component.html
{{variab}}
{{variab *2}}
输出:
参考: https://angular.io/api/common/NgIf