在2个子组件之间共享对象 [英] Share object between 2 child components
问题描述
我有一个主要组成部分,其中包含3个子组成部分.
I have a main component with 3 sub-components.
主要组件的HTML结构如下:
Main component HTML structure looks like this:
<div class="container-fluid">
<div class="row">
<reserved-parking></reserved-parking>
<available-parking></available-parking>
<profile></profile>
</div>
</div>
例如,当用户从可用停车组件中选择停车时,应将信息发送到预留停车组件.因此,我需要将JSON对象从available-parking传递到reserved-parking组件.
For instance, when a user selects parking from available-parking component information should be sent to reserved-parking component. So, I need to pass a JSON object from available-parking to reserved-parking component.
我尝试使用@Input
,但是没有运气.仅从父母到孩子,反之亦然.
I've tried to use @Input
, but no luck. Only from parent to child and vice-versa.
谢谢.
推荐答案
像这样使用事件发射器和双向绑定.
Use event emitters and two-way binding like this.
父级组件
@Component(){
...
}
export class ParentComp{
parkingLots: Array<any> = [one,two,three];
constructor(){}
}
父模板
<div class="container-fluid">
<div class="row">
<reserved-parking [(data)]="parkingLots"></reserved-parking>
<available-parking [(data)]="parkingLots"></available-parking>
<profile></profile>
</div>
</div>
预留停车位
@Component(){
selector: 'reserved-parking',
inputs: ['data'],
outputs: ['dataChange'],
...
}
export class ReservedParking{
data: Array<any>;
dataChange: EventEmitter<Array<any>> = new EventEmitter();
constructor(){}
ngOnInit() {
this.data.push('four');
this.dataChange.emit(this.data);
}
}
可用的停车组件
@Component(){
selector: 'available-parking',
inputs: ['data'],
outputs: ['dataChange'],
...
}
export class AvailableParking{
data: Array<any>;
dataChange: EventEmitter<Array<any>> = new EventEmitter();
constructor(){}
ngOnInit() {
console.log(this.data);
// you can also update it here and then do
// this.dataChange.emit(this.data); to send it out
}
}
注意:导入所需的任何内容,数据可以根据需要任意更改,主要是通过执行dataChange.emit(this.data)
note: import anything required, data is arbitrary change it according to your needs, main thing is to emit the value after modification by doing dataChange.emit(this.data)
这篇关于在2个子组件之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!