组件通信是 Angular 开发中的核心技能,掌握它能让你更好地构建复杂应用。以下是常见的通信方式:

1. 父组件 → 子组件

使用 @Input() 装饰器传递数据
🎯 示例:

// 父组件
<app-child [data]="parentData"></app-child>
Parent_to_Child

2. 子组件 → 父组件

通过 @Output() 和事件发射实现
🎯 示例:

// 子组件
@Output() valueChange = new EventEmitter();
this.valueChange.emit('新值');
Child_to_Parent

3. 兄弟组件通信

借助服务(Service)作为中间桥梁
🎯 示例:

// 共享服务
@Injectable()
export class SharedService {
  public data: string;
}
Service_Communication

4. 跨层级通信

使用 @ViewChildren@ContentChildren 获取子组件引用
🎯 示例:

@ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

5. 服务通信(全局)

通过服务共享数据,适用于任意组件
🎯 示例:

// 全局服务
@Injectable()
export class AppService {
  private data: string;
  setData(val: string) { this.data = val; }
  getData() { return this.data; }
}
Service_Communication

需要进一步了解组件生命周期?👉 点击这里查看组件生命周期教程