Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Observing @Output Event Emitters in Child Components?

How should be go about using / observing parent @Output() event emitters in child components?

For example in this demo the child component uses the @Output onGreetingChange like this:

<app-greeting [greeting]="onGreetingChange | async"></app-greeting>

And this will work if onGreetingChange emits in the AfterViewInit life cycle hook.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  ngAfterViewInit() {
    this.onGreetingChange.emit('Hola');
  }

However that produces the an ExpressionChangedAfterItHasBeenCheckedError error.

Is there a way to get to this to work without producing the error?

I tried emitting in both the constructor and OnInit. Thoughts?

>Solution :

You can trigger the change detection manually, using detectChanges()

My guess is that since its a non conventional way of changing an @Input change detection is missing the changes, so we need to run it manually!

  ngAfterViewInit() {
    this.onGreetingChange.emit('Hola');
    this.cdr.detectChanges();
  }

stackblitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading