组件与模板
selector、templateUrl、数据绑定。
35 分钟
组件与模板
Angular 组件 = @Component 装饰的类 + HTML 模板 + 样式,通过 selector 嵌入页面。通信模式与 Vue 3 核心 一致:Input 向下、Output 向上;对比 React 核心 的 props 与回调。
学习目标
- 定义 Standalone 组件与 selector
- 使用插值、属性绑定、事件绑定
- 掌握
@Input/@Output父子通信
核心内容
组件定义
import { Component, Input, Output, EventEmitter } from "@angular/core";
@Component({
selector: "app-track-card",
standalone: true,
template: `
<article (click)="select.emit(slug)">
<h2>{{ title }}</h2>
<a [href]="'/tracks/' + slug">进入</a>
</article>
`,
styles: [`article { cursor: pointer; }`],
})
export class TrackCardComponent {
@Input({ required: true }) title!: string;
@Input({ required: true }) slug!: string;
@Output() select = new EventEmitter<string>();
}
TypeScript 严格模式见 TypeScript 核心 的 ! 与接口定义。
父组件组合
@Component({
selector: "app-track-grid",
standalone: true,
imports: [TrackCardComponent],
template: `
@for (t of tracks; track t.slug) {
<app-track-card [title]="t.title" [slug]="t.slug" (select)="onSelect($event)" />
}
`,
})
export class TrackGridComponent {
tracks = [
{ title: "Angular 核心", slug: "angular-essentials" },
{ title: "React 核心", slug: "react-essentials" },
];
onSelect(slug: string) {
console.log("选中", slug);
}
}
绑定速查:{{ }} 插值、[prop] 属性、(event) 事件、[(ngModel)] 双向。内容投影用 <ng-content>,类似 Vue <slot>。
练习
- 拆出
PageLayout组件,用<ng-content select="[header]">传标题 - 子组件
Output触发close,父组件清空选中项
小结
组件 = 类 + 模板 + 样式;Input/Output 管通信。 下一课内置指令。
加载本节练习…