简体   繁体   中英

Parent/Child Component Interaction - Return values using EventEmitter angular2

1) I have a child component (CounterComponent) that emits an event using @Output 2) The child component also has an Input parameter callBackCancelled. 3) The parent component (AppComponent) sets the callBackCancelled value to "true" but in the child component that value is still undefined.

See the plunker sample https://plnkr.co/edit/2vnTUEDyBKT59GDTvkEJ

callbackFunction(e) {
alert('emitting event from child callback button component');
this.callback.emit(e);

alert('Now in child component, this value should be true, but it is:  ' + this.callBackCancelled);

}

Can someone help?

Practically, this alert('Now in child component, this value should be true, but it is: ' + this.callBackCancelled); gets called before the below:

btncallback(event) {
    console.log(event);
    this.callBackCancelled = event;
    alert('Parent component sets the callBackCancelled value to true.');
  }

so by that time, this.callBackCancelled is still undefined. There are couple of ways to get this to work.

  1. A Service
  2. Implements ngOnChanges()

Here's an example of the latter:

  1. Get rid of () from [(callBackCancelled)]
  2. implements the following: https://plnkr.co/edit/qDG0dK01USbN1ifVFXvl?p=info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM