CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
Angular 路线图实战/课时/组件与生命周期
RawBlame
课时目录12 节

Angular 路线图实战

  1. 01Angular 入门与 CLI
  2. 02组件与生命周期
  3. 03模板与数据绑定
  4. 04指令与管道
  5. 05表单
  6. 06服务与依赖注入
  7. 07HttpClient 与安全
  8. 08Router 与懒加载
  9. 09RxJS 与 Signals
  10. 10SSR、测试与 i18n
  11. 11NgModule 与库
  12. 12综合练习

组件与生命周期

组件解剖、@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 对照

AngularReactNext.js
@Inputpropsprops(Server/Client 组件)
@Output + EventEmitter回调 props回调 props
ngOnInituseEffect 首次useEffect
@ViewChilduseRefuseRef

练习

  • 父组件传 title/slug,子组件 Output 触发选中事件
  • 在 ngOnDestroy 中取消 RxJS 订阅

小结

组件 = 类 + 模板;Input 向下、Output 向上;钩子管初始化与清理。 下一课模板绑定。

加载本节练习…
← 上一课Angular 入门与 CLI下一课 →模板与数据绑定