Angular父子组件间通信的方式有很多种,比如通过@Input
和@Output
,ViewChild
和ViewChildren
等。今天我们来详细讨论一下这几种方式的使用。
@Input和@Output
这是最常见的方式,适用于父子组件之间的单向或双向数据传递。
(1) 父组件向子组件传递数据(@Input)
父组件可以通过 @Input 装饰器将数据传递给子组件。
步骤:
- 在子组件中使用 @Input 定义一个输入属性。
- 在父组件模板中通过属性绑定将数据传递给子组件。
代码示例:
子组件 (child.component.ts):
1 | import { Component, Input } from '@angular/core'; |
父组件 (parent.component.html):
1 | <app-child [message]="'Hello from Parent!'"></app-child> |
(2) 子组件向父组件传递数据(@Output 和 EventEmitter)
子组件可以通过 @Output 和 EventEmitter 向父组件发送事件和数据。
步骤:
- 在子组件中定义一个 @Output 属性,并使用 EventEmitter 发送数据。
- 在父组件中监听子组件的事件并处理数据。
代码示例:
子组件 (child.component.ts):
1 | import { Component, Output, EventEmitter } from '@angular/core'; |
父组件 (parent.component.html):
1 | <app-child (messageEvent)="receiveMessage($event)"></app-child> |
父组件 (parent.component.ts):
1 | export class ParentComponent { |
ViewChild和ViewChildren
父组件可以通过 @ViewChild 或 @ViewChildren 直接访问子组件的属性和方法。
步骤:
- 在父组件中使用 @ViewChild 获取子组件的实例。
- 直接调用子组件的方法或访问其属性。
代码示例:
子组件 (child.component.ts):
1 | import { Component } from '@angular/core'; |
父组件 (parent.component.ts):
1 | import { Component, ViewChild } from '@angular/core'; |
使用SharedService
如果父子组件之间的通信比较复杂,可以使用共享服务来管理数据。详情见这里