在本快速教程中,您将学习如何在Angular 9/8应用程序中使用ngIf。
看一个简单的例子。
假设,我们有以下Angular 9组件 src/app/contact-list/contact-list.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'contact-list',
templateUrl: './contact-list.component.html',
styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent {
showActions: boolean = false;
contacts: <> = [
{name: "test1", email:"test1@test1.com"},
{name: "test2", email:"test1@test2.com"},
{name: "test3", email:"test1@test3.com"},
{name: "test4", email:"test1@test4.com"}
]
}
在Angular 9中使用ngIf
在组件的模板中,您需要使用ngIf指令,并根据showActions变量的值显示或隐藏action 按钮。以下是模板的示例:
<h1>Contact List</h1>
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th *ngIf="showActions">Actions</th>
</thead>
<tbody>
<tr *ngFor="let contact of contacts">
<td>
{{contact.name}}
</td>
<td>
{{contact.email}}
</td>
<td *ngIf="showActions">
<button>Delete</button>
<button>Update</button>
</td>
</tr>
</tbody>
</table>
相关文章