组件与生命周期
组件解剖、@Input/@Output、ViewChild。
35 分钟
组件与生命周期
/roadmaps/angular「Components」节点核心:组件 = @Component 装饰的类 + 模板 + 样式,通过 selector 嵌入 DOM。通信模式与 React 核心 的 props/callback、Vue 3 核心 的 props/emit 一致。
学习目标
- 定义 Standalone 组件与
@Input/@Output - 使用生命周期钩子
ngOnInit、ngOnDestroy - 用
@ViewChild访问子组件或 DOM 元素
核心概念
组件定义与通信
import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from "@angular/core";
@Component({
selector: "app-track-card",
standalone: true,
template: `
<article (click)="select.emit(slug)">
<h2>{{ title }}</h2>
</article>
`,
})
export class TrackCardComponent implements OnInit, OnDestroy {
@Input({ required: true }) title!: string;
@Input({ required: true }) slug!: string;
@Output() select = new EventEmitter<string>();
ngOnInit() { /* 初始化:拉数据、订阅 */ }
ngOnDestroy() { /* 清理订阅,防内存泄漏 */ }
}
ViewChild
@ViewChild("searchInput") searchInput!: ElementRef<HTMLInputElement>;
focusSearch() {
this.searchInput.nativeElement.focus();
}
与 React/Next 对照
| Angular | React | Next.js |
|---|---|---|
@Input | props | props(Server/Client 组件) |
@Output + EventEmitter | 回调 props | 回调 props |
ngOnInit | useEffect 首次 | useEffect |
@ViewChild | useRef | useRef |
练习
- 父组件传
title/slug,子组件Output触发选中事件 - 在
ngOnDestroy中取消 RxJS 订阅
小结
组件 = 类 + 模板;Input 向下、Output 向上;钩子管初始化与清理。 下一课模板绑定。