最常用的内置结构指令
COMMON BUILT-IN STRUCTURAL DIRECTIVES | DETAILS |
---|---|
NgIf | Conditionally creates or disposes of subviews from the template. // 有条件地创建或处置模板中的子视图 |
NgFor | Repeat a node for each item in a list. // 为列表中的每个项目重复一个节点 |
NgSwitch | A set of directives that switch among alternative views. // 切换不同视图的指令集 |
要使用内置结构指令,请导入 CommonModule 并将其添加到组件的导入列表中
import {CommonModule} from '@angular/common';
/* . . . */
@Component({
standalone: true,
/* . . . */
imports: [
CommonModule, // <-- import into the component
/* . . . */
],
})
export class AppComponent implements OnInit {
/* . . . */
}
通过将 NgIf 指令应用于宿主元素,可以添加或删除元素
当 NgIf 为 false 时,Angular 会从 DOM 中移除一个元素及其后代。然后,Angular 会释放它们的组件,从而释放内存和资源
<app-item-detail *ngIf="isActive" [item]="item"></app-item-detail>
如果属性为空,Angular 不会显示
<div *ngIf="nullCustomer">Hello, <span>{{nullCustomer}}</span></div>
使用 NgFor 指令来展示一个项目列表
<div *ngFor="let item of items">{{item.name}}</div>
获取 *ngFor 的索引
在 *ngFor 中,将一个分号和 let i=index 添加到简写形式中。以下示例将索引获取到一个名为i的变量中,并将其与项目名称一起显示
<div *ngFor="let item of items; let i=index">{{i + 1}} - {{item.name}}</div>
使用 *ngFor trackBy 跟踪项目
通过跟踪项目列表的变化,减少应用程序对服务器的调用次数。使用 ngFor 的 trackBy 属性,Angular 可以只更改和重新渲染那些已更改的项目,而不是重新加载整个项目列表
<div *ngFor="let item of items; trackBy: trackByItems">
({{item.id}}) {{item.name}}
</div>
trackByItems(index: number, item: Item): number {
return item.id;
}
在没有 DOM 元素的情况下托管指令
Angular 的 <ng-container>
是一个分组元素,不会干扰样式或布局,因为 Angular 不会将其放在 DOM 中
当没有单个元素来托管指令时,可以使用 <ng-container>
<p>
I turned the corner
<ng-container *ngIf="hero">
and saw {{hero.name}}. I waved
</ng-container>
and continued on my way.
</p>
使用 NgSwitch 切换视图
与 JavaScript 的 switch 语句类似,NgSwitch 根据一个切换条件从多个可能的元素中显示一个元素。Angular 只将选定的元素放入 DOM 中
NgSwitch 由三个指令组成:
NGSWITCH DIRECTIVES | DETAILS |
---|---|
NgSwitch | An attribute directive that changes the behavior of its companion directives. // 属性指令,可更改其配套指令的行为 |
NgSwitchCase | Structural directive that adds its element to the DOM when its bound value equals the switch value and removes its bound value when it doesn't equal the switch value. // 结构指令,当其绑定值等于开关值时将其元素添加到 DOM,当其绑定值不等于开关值时将其移除 |
NgSwitchDefault | Structural directive that adds its element to the DOM when there is no selected // 结构指令,用于在没有选中 NgSwitchCase 时将其元素添加到 DOM 中 |
<div [ngSwitch]="currentItem.feature">
<app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item>
<app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item>
<app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item>
<app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item>
<!-- . . . -->
<app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item>
</div>
Switch 指令也适用于内置的 HTML 元素和 Web 组件。例如,你可以将 <app-best-item> 切换情况替换为以下 < div>:
<div *ngSwitchCase="'bright'"> Are you as bright as {{currentItem.name}}?</div>