I am using Angular 7 and use "ng serve" to launch the app. I have parent-child components and parent component has a button on click flips a boolean property value. if that boolean property is true child component is displayed (*ngIf). From the child component, I emit an event that calls the function in the parent which flips the boolean property value in Parent causing the child component to be removed (*ngIf)
Parent component:
Parent.component.ts
capture: boolean = false;
onCapture () {
console.log("onCapture called")
this.capture = !this.capture;
}
Parent.component.html
<app-capture *ngIf="capture ==true" (closeCapturePage)="onCapture()"></app-capture>
<label>
<img src="/assets/img/camera.svg" alt="" width="32" height="32" title="Open window">
<input type="button" (click)="onCapture()" id="capture" style="display: none">
</label>
Child-component.ts
@Output() closeCapturePage = new EventEmitter<void>();
closePage() {
this.closeCapturePage.emit();
}
I can see the child component emits event successfully however encountering the error ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'
I tried the solutions suggested in similar threads such as implementing ngAfterViewChecked in parent component but no luck.
show = false;
ngAfterViewChecked(): void {
let show = this.capture;
if (show != this.show) {
this.show = show;
this.cdRef.detectChanges();
}
}
Stackblitz Example: https://stackblitz.com/edit/angular-8efhdm (NOTE: the simple example was not reproducing, so I added the actual code that start the camera but doesn't record anything, no privacy issues!)