在Angular中,组件之间的数据共享可以通过以下几种方式实现:
父组件:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Parent Component
Received message: {{receivedMessage}}
`
})
export class ParentComponent {
message: string;
receivedMessage: string;
receiveMessage(message: string) {
this.receivedMessage = message;
}
}
子组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Child Component
Input message from parent: {{inputMessage}}
`
})
export class ChildComponent {
@Input() inputMessage: string;
@Output() outputMessage = new EventEmitter();
sendMessage() {
this.outputMessage.emit('Hello from child component');
}
}
共享服务:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
sharedData: string;
constructor() { }
}
组件1:
import { Component } from '@angular/core';
import { DataService } from 'path-to-data-service';
@Component({
selector: 'app-component1',
template: `
Component 1
`
})
export class Component1 {
constructor(public dataService: DataService) { }
}
组件2:
import { Component } from '@angular/core';
import { DataService } from 'path-to-data-service';
@Component({
selector: 'app-component2',
template: `
Component 2
Shared data: {{dataService.sharedData}}
`
})
export class Component2 {
constructor(public dataService: DataService) { }
}
请确保在模块的providers数组中提供共享服务,以便在整个应用程序中使用。
这些方法都可以实现组件之间的数据共享,选择适合你需求的方法进行实现。