Angular 组件间通信是构建复杂应用的核心能力,以下是常见实现方式及示例:
1. 父子组件通信
- @Input():父组件向子组件传递数据
- @Output():子组件向父组件发送事件
2. 兄弟组件通信
- 通过父组件中转:
// 父组件 @Component({ selector: 'app-parent' }) export class ParentComponent { constructor(private child1: Child1Component, private child2: Child2Component) {} }
- 使用 EventEmitters 创建自定义事件
3. 非父子组件通信
- Service 共享:通过共享服务传递数据
- RxJS Subject:实现广播模式通信
- @ViewChild/@ViewChildren:访问子组件实例
4. 高级技巧
- BehaviorSubject:保持最新值的通信方式
- Event Bus 模式:使用 NgZone 实现跨组件事件
- Angular_Component_Interaction:深入理解组件交互原理
了解更多组件交互高级模式 ➡️