指令与管道
结构/属性指令、内置与自定义 Pipe。
30 分钟
指令与管道
路线图「Directives & Pipes」:结构型指令 增删 DOM 节点,属性型指令 改元素外观或行为;管道(Pipe) 在模板中做格式化(日期、货币、大小写)。存量项目常见 *ngIf/*ngFor,新项目优先 @if/@for。
学习目标
- 区分结构型与属性型指令
- 使用内置 Pipe 与自定义 Pipe
- 读懂存量代码中的
*ngDirectives与CommonModule
核心概念
结构型与属性型
@Component({
standalone: true,
imports: [CommonModule, DatePipe],
template: `
@if (user) {
<p>欢迎,{{ user.name | uppercase }}</p>
}
<ul>
@for (t of tracks; track t.slug) {
<li [class.highlight]="t.featured">{{ t.title | titlecase }}</li>
} @empty {
<li>暂无课程</li>
}
</ul>
<span>{{ updatedAt | date: "yyyy-MM-dd" }}</span>
`,
})
export class DirectiveDemoComponent {
user = { name: "learner" };
updatedAt = new Date();
tracks = [{ slug: "ang-intro", title: "angular intro", featured: true }];
}
自定义 Pipe
@Pipe({ name: "slugify", standalone: true })
export class SlugifyPipe implements PipeTransform {
transform(value: string): string {
return value.toLowerCase().replace(/\s+/g, "-");
}
}
模板:{{ title | slugify }}。
与 React/Next 对照
| Angular | React | 说明 |
|---|---|---|
@if / *ngIf | {cond && <…>} | 条件渲染 |
@for / *ngFor | .map() | 列表 |
date pipe | Intl.DateTimeFormat / dayjs | 格式化 |
| 自定义 pipe | 工具函数 | 模板内调用 |
Next.js 多在 JSX 中直接调函数;Angular 管道更声明式、可纯函数缓存(pure: true)。
练习
- 写
truncate管道,超长标题显示省略号 - 用
[ngClass]切换「featured / normal」样式