Angular 组件通信是 Angular 框架中一个非常重要的概念。它允许组件之间进行数据传递和交互,从而实现复杂的应用逻辑。

通信方式

Angular 提供了多种组件通信的方式,以下是一些常用的方法:

  • 属性(Properties):父组件向子组件传递数据。
  • 事件(Events):子组件向父组件发送消息。
  • 服务(Services):通过服务来共享数据或功能。
  • 输入输出属性(Input/Output):使用 @Input()@Output() 装饰器。

属性传递

父组件可以通过属性向子组件传递数据。例如:

<!-- 父组件 -->
<app-child [childProperty]="parentData"></app-child>

<!-- 子组件 -->
@Component({
  selector: 'app-child',
  template: `<div>{{ childProperty }}</div>`
})
export class ChildComponent {
  @Input() childProperty: string;
}

事件传递

子组件可以通过发出事件向父组件传递消息。例如:

<!-- 子组件 -->
<app-child (childEvent)="handleChildEvent($event)"></app-child>

<!-- 父组件 -->
@Component({
  selector: 'app-parent',
  template: `<app-child (childEvent)="handleChildEvent($event)"></app-child>`
})
export class ParentComponent {
  handleChildEvent(event: any) {
    console.log(event);
  }
}

服务共享

服务是 Angular 中共享数据或功能的一种方式。例如:

// 服务
@Injectable({
  providedIn: 'root'
})
export class DataService {
  getData() {
    return 'Hello from service!';
  }
}

// 组件
@Component({
  selector: 'app-component',
  template: `<div>{{ data }}</div>`
})
export class AppComponent {
  @Inject(DataService) private dataService: DataService;

  constructor() {
    this.data = this.dataService.getData();
  }

  data: string;
}

扩展阅读

更多关于 Angular 组件通信的信息,请参考以下链接:/Angular 组件通信


Angular Component Communication