在 Angular 应用中,组件之间的通信是构建动态和复杂用户界面的关键。Angular 提供了多种方法来实现组件间的传值与交互。本文档将详细介绍如何在 Angular 项目中使用这些方法。
子组件通过 @Input()
装饰器接收父组件的数据。
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>{{data}}</p>`
})
export class ChildComponent {
@Input() data: string;
}
<!-- parent.component.html -->
<app-child [data]="parentData"></app-child>
EventEmitter
发出事件。父组件监听子组件发出的事件,并进行相应的处理。
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="emitValue()">Click me</button>`
})
export class ChildComponent {
@Output() valueChange = new EventEmitter<string>();
emitValue() {
this.valueChange.emit('Hello from child');
}
}
<!-- parent.component.html -->
<app-child (valueChange)="handleValue($event)"></app-child>
当两个组件之间没有直接的父子关系时,可以通过一个共享的服务来交换数据。
Subject
或 BehaviorSubject
)。在需要接收数据的组件中订阅该服务的数据变化。
// data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private dataSource = new BehaviorSubject<string>('default message');
currentMessage = this.dataSource.asObservable();
changeMessage(message: string) {
this.dataSource.next(message);
}
}
服务不仅可用于兄弟组件间的通信,还可以作为全局状态管理工具,帮助你组织和共享应用中的数据。
确保你的服务在根模块或需要使用的模块中声明 providedIn: 'root'
,这样 Angular 会自动提供并单例化你的服务。
以上内容简要介绍了 Angular 中组件间传值的基本方法。根据实际应用场景的不同,你可能需要组合使用这些方法以满足更复杂的业务需求。希望这份文档能帮助你更好地理解和实践 Angular 组件间的交互。