Angular 10 是一个强大的前端框架,它提供了多种组件通信的方式。以下是一些常用的组件通信方法:

1. 属性(Properties)

使用属性可以将数据从父组件传递到子组件。

// 父组件
<app-child [myProperty]="value"></app-child>

// 子组件
export class ChildComponent {
  @Input() myProperty: string;
}

2. 事件(Events)

子组件可以通过发出事件来通知父组件。

// 子组件
export class ChildComponent {
  @Output() myEvent = new EventEmitter<string>();

  notifyParent() {
    this.myEvent.emit('data');
  }
}

// 父组件
<app-child (myEvent)="handleEvent($event)"></app-child>

3. 服务(Services)

服务是 Angular 中实现组件间通信的常用方式。

// 服务
@Injectable()
export class MyService {
  private data = 'initial data';

  getData() {
    return this.data;
  }
}

// 组件
this.myService.getData().subscribe(data => {
  console.log(data);
});

4. 观察者(Observables)

使用 Observables 可以实现异步数据流。

// 服务
@Injectable()
export class MyService {
  getData() {
    return this.http.get('/api/data').pipe(
      map(response => response.data),
      catchError(this.handleError)
    );
  }
}

// 组件
this.myService.getData().subscribe(data => {
  console.log(data);
});

5. 输入属性与输出事件

这是一种结合属性和事件的方法,可以同时实现数据的双向绑定。

// 子组件
export class ChildComponent {
  @Input() myProperty: string;
  @Output() myEvent = new EventEmitter<string>();

  constructor() {
    this.myProperty = 'initial value';
  }

  notifyParent() {
    this.myEvent.emit(this.myProperty);
  }
}

// 父组件
<app-child [myProperty]="parentValue" (myEvent)="handleEvent($event)"></app-child>

更多关于 Angular 组件通信的细节,请访问我们的Angular 组件通信深入指南

Angular Logo