Angular父子组件间通信的方式有很多种,比如通过@Input和@Output,ViewChild和ViewChildren等。今天我们来详细讨论一下这几种方式的使用。
这是最常见的方式,适用于父子组件之间的单向或双向数据传递。
(1) 父组件向子组件传递数据(@Input)
父组件可以通过 @Input 装饰器将数据传递给子组件。
步骤:
- 在子组件中使用 @Input 定义一个输入属性。
- 在父组件模板中通过属性绑定将数据传递给子组件。
代码示例:
子组件 (child.component.ts):
1 2 3 4 5 6 7 8 9
| import { Component, Input } from '@angular/core';
@Component({ selector: 'app-child', template: `<p>Message from parent: {{ message }}</p>` }) export class ChildComponent { @Input() message!: string; }
|
父组件 (parent.component.html):
1
| <app-child [message]="'Hello from Parent!'"></app-child>
|
(2) 子组件向父组件传递数据(@Output 和 EventEmitter)
子组件可以通过 @Output 和 EventEmitter 向父组件发送事件和数据。
步骤:
- 在子组件中定义一个 @Output 属性,并使用 EventEmitter 发送数据。
- 在父组件中监听子组件的事件并处理数据。
代码示例:
子组件 (child.component.ts):
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { Component, Output, EventEmitter } from '@angular/core';
@Component({ selector: 'app-child', template: `<button (click)="sendMessage()">Send Message to Parent</button>` }) export class ChildComponent { @Output() messageEvent = new EventEmitter<string>();
sendMessage() { this.messageEvent.emit('Hello from Child!'); } }
|
父组件 (parent.component.html):
1 2
| <app-child (messageEvent)="receiveMessage($event)"></app-child> <p>Message from child: {{ receivedMessage }}</p>
|
父组件 (parent.component.ts):
1 2 3 4 5 6 7
| export class ParentComponent { receivedMessage = '';
receiveMessage(message: string) { this.receivedMessage = message; } }
|
ViewChild和ViewChildren
父组件可以通过 @ViewChild 或 @ViewChildren 直接访问子组件的属性和方法。
步骤:
- 在父组件中使用 @ViewChild 获取子组件的实例。
- 直接调用子组件的方法或访问其属性。
代码示例:
子组件 (child.component.ts):
1 2 3 4 5 6 7 8 9 10 11 12 13
| import { Component } from '@angular/core';
@Component({ selector: 'app-child', template: `<p>Child Component</p>` }) export class ChildComponent { message = 'Hello from Child!';
greet() { return 'Greeting from Child!'; } }
|
父组件 (parent.component.ts):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { Component, ViewChild } from '@angular/core'; import { ChildComponent } from './child.component';
@Component({ selector: 'app-parent', template: ` <app-child></app-child> <button (click)="callChildMethod()">Call Child Method</button> <p>Message from child: {{ childMessage }}</p> ` }) export class ParentComponent { @ViewChild(ChildComponent) child!: ChildComponent; childMessage = '';
callChildMethod() { this.childMessage = this.child.greet(); } }
|
使用SharedService
如果父子组件之间的通信比较复杂,可以使用共享服务来管理数据。详情见这里