组件A内部有2个组件:
<div class="classStyleLeft">
<app-picture [IdSectionPicture]="2" [PData]="modelPage"></app-picture>
</div>
<div class="classStyleRight">
<app-list [IdSectionList]="2" [PData]="modelPage"></app-list>
</div>
在组件 app-list
中,从列表中选择一个项目并单击方法 showInfo
:
<ul *ngFor="let value of PData.content[IdSectionList].content; let valueIndex = index;">
<li (click)="showInfo(IdSectionList, valueIndex)">
<b>{{value.value}}</b>
</li>
</ul>
我想要将方法参数 showInfo
传递给组件 app-picture
。组件内容app-picture
:
<div>{{PData.content[IdSectionList].value[valueIndex].value}}</div>
我不知道怎么做。
我会寻求帮助。 谢谢
最佳答案
使用服务共享数据是不够的,因为必须监听事件。
由于它是同级组件,因此使用 BehaviorSubject
创建一个服务为:
export class InfoService{
private infoSubject = new BehaviorSubject<any>({id: '',value: ''});
showInfoEventEmitter(data){
this.infoSubject.next(data);
}
showInfoEventListener(){
return this.infoSubject.asObservable();
}
}
然后在组件中使用它作为
app-list.component
constructor(public infoSvc: InfoService){}
showInfo(IdSectionList, valueIndex){
this.infoSvc.showInfoEventEmitter({id:IdSectionList, value: valueIndex})
}
并且在app-picture.component
eventSubscription: Subscription;
constructor(public infoSvc: InfoService){}
ngOnInit(){
this.eventSubscription = this.infoSvc.showInfoEventListener().subscribe(res => {
console.log(res); // you have the event here
})
}
ngOnDestroy(){
this.eventSubscription.unsubscribe(); // to stop listening to this event after component is destroyed
}
关于javascript - 组件之间的数据传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303137/