Search code examples
angulareventemitter

angular 2 child component not getting input data


in my case i am trying to emit an event with data from one child of the parent to another child of the same parent. basically between siblings.

the code looks like

Child A

 @Output() makeIsrCall = new EventEmitter<LeadModel>()
 startCall(){
    this.makeIsrCall.emit(this.lead)
}

Parent .html

    <app-isr-call-toolbar *ngIf="core.isrCallInProgress == true" [data]="isrContact"></app-isr-call-toolbar>
 <app-edit-opty-workarea  [objId]="tb.id" [objType]="tb.objectType" (makeIsrCall)="makeCall($event)"></app-edit-opty-workarea>

.ts

 isrContact:any
 makeCall(lead:LeadModel){
    this.isrContact = lead
  }

Child B .ts

@Input() data:any
 constructor(private core:CoreStructureService) { 
    console.log('called construct for isr component')

    alert(this.data) //this comes undefined
  }

Solution

  • The constructor is looong done before the data arrives

    Either use ngOnChanges lifecycle callback

    @Input() data:any
    
    constructor(private core:CoreStructureService) { 
        console.log('called construct for isr component')
    }
    
    ngOnChanges() {
        alert(this.data) //this comes undefined
    }
    

    or make data a setter

    @Input() set data(value:any) {
        this._data = value;
        alert(this._data) //this comes undefined
    }
    
    constructor(private core:CoreStructureService) { 
        console.log('called construct for isr component')
    }