模板与数据绑定
插值、属性/事件绑定、Control Flow。
35 分钟
模板与数据绑定
路线图「Templates & Data Binding」:模板 声明 UI,绑定 连接组件状态与 DOM。Angular 提供插值、属性、事件、双向四类绑定;Angular 17+ Control Flow(@if/@for)替代部分经典指令。
学习目标
- 掌握
{{ }}、[prop]、(event)、[(ngModel)]四类绑定 - 使用
@if/@for/@switch控制流 - 理解变更检测如何让 UI 随状态更新
核心概念
绑定语法速查
@Component({
selector: "app-binding-demo",
standalone: true,
imports: [FormsModule],
template: `
<p>标题:{{ title }}</p>
<a [href]="'/tracks/' + slug">详情</a>
<button (click)="count = count + 1">点击 {{ count }}</button>
<input [(ngModel)]="keyword" placeholder="搜索" />
@if (count > 3) {
<span>已超过 3 次</span>
}
@for (t of tracks; track t.slug) {
<li>{{ t.title }}</li>
}
`,
})
export class BindingDemoComponent {
title = "Angular 路线图";
slug = "angular-roadmap-essentials";
count = 0;
keyword = "";
tracks = [{ slug: "react-essentials", title: "React 核心" }];
}
变更检测
Angular 默认 Zone.js 监听异步事件后全树检测;新应用可启用 Zoneless + Signals 减少开销。声明式 UI 原则与 React 相同:UI = f(state)。
与 React/Next 对照
| Angular | React | Vue |
|---|---|---|
{{ x }} | {x} in JSX | {{ x }} |
[disabled]="x" | disabled={x} | :disabled |
(click)="fn()" | onClick={fn} | @click |
[(ngModel)] | 受控 input | v-model |
@for | .map() | v-for |
练习
- 用
@for渲染课程列表,加track表达式 - 双向绑定搜索框,过滤列表标题