Share object between 2 child components

后端 未结 2 2086
情话喂你
情话喂你 2021-02-11 08:12

I have a main component with 3 sub-components.

Main component HTML structure looks like this:

2条回答
  •  一向
    一向 (楼主)
    2021-02-11 08:31

    Use event emitters and two-way binding like this.

    parent component

    @Component(){
    ...
    }
    export class ParentComp{
      parkingLots: Array =  [one,two,three];
      constructor(){}
    }
    

    parent template

    reserved-parking component

    @Component(){
    selector: 'reserved-parking',
    inputs: ['data'],
    outputs: ['dataChange'],
    ...
    }
    export class ReservedParking{
      data: Array;
      dataChange: EventEmitter> = new EventEmitter();
    
      constructor(){}
    
      ngOnInit() {
        this.data.push('four');
        this.dataChange.emit(this.data);
      }
    }
    

    available-parking component

    @Component(){
    selector: 'available-parking',
    inputs: ['data'],
    outputs: ['dataChange'],
    ...
    }
    export class AvailableParking{
      data: Array;
      dataChange: EventEmitter> = 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
      }
    }
    

    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)

提交回复
热议问题