要在组件之间实现共享组件的双向绑定,需要通过共享一个服务来实现数据的交互。以下是一个示例,其中两个组件(ParentComponent和ChildComponent)共享一个服务(SharedService):
shared.service.ts:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(data: any) {
this.messageSource.next(data);
}
}
parent.component.ts:
import { Component } from '@angular/core';
import { SharedService } from './shared.service';
@Component({
selector: 'app-parent',
template: `
Parent Component
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
message: string;
constructor(private sharedService: SharedService) { }
sendMessage() {
this.sharedService.changeMessage(this.message);
}
}
child.component.ts:
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared.service';
@Component({
selector: 'app-child',
template: `
Child Component
{{message}}
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
message: string;
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.currentMessage.subscribe(data => {
if (data) {
this.message = data;
}
});
}
}
在这个示例中,ParentComponent和ChildComponent共享一个名为SharedService的服务。当用户在ParentComponent中输入消息时,它通过SharedService更改,并由ChildComponent显示。这是通过订阅SharedService.currentMessage属性来实现的。任何