在AngularJS中,如何在特定条件为真时显示/隐藏数据
在AngularJS中,为了隐藏或显示数据或内容,我们可以使用*ngIf结构指令。通过使用它,我们可以评估条件,然后*ngIf基于条件显示内容。例如,如果*ngIf的条件为真,那么内容将被显示,如果条件为假,则不显示内容。
步骤:
- 为了给出一个清晰而详细的观点,我将用一个例子来解释这个概念。
- 考虑到我们在.ts文件中有一个对象数组,数组中的对象包含一个技术和非技术公司的列表。
- 这个实验的目的是显示所有技术公司的数据,并隐藏所有非技术公司的数据。
- 为了遍历数组,我们将在.html文件中使用*ngFor指令。
- 一旦你完成了实施,就启动服务器。
例子:这个例子描述了AngularJS中基于特定条件的数据渲染。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
companies = [
{
name: 'Microsoft',
isTechnical: true,
},
{
name: 'GeeksforGeeks',
isTechnical: true,
},
{
name: 'Netflix',
isTechnical: false,
},
{
name: 'TCS',
isTechnical: true,
},
];
}
import { NgModule } from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
<h1 style="color:green">GeeksforGeeks</h1>
<h3>
Display or Hide data when the
particular condition is true in
AngularJS
</h3>
<ol>
<li *ngFor="let company of companies">
<i *ngIf="company.isTechnical">
{{ company.name }}
</i>
</li>
</ol>
输出:你可以清楚地看到第3项是隐藏的,因为它的条件是假的。为了给出一个更明显的例子,我把它留空了。