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.
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?
2
Answers
You can trigger the
change detection
manually, usingdetectChanges()
stackblitz
In general
ngAfterViewInit
life cycle hook is not the best place to initiate the value.You should use
ngDoInit
BUT
You can always use
BehaviorSubject
instead ofEventEmitter
. See this:https://stackblitz.com/edit/stackblitz-starters-bncmrb?file=src%2Fmain.ts
Main App
HTML
Child one
Child two