Search code examples
angulartypescriptangular-changedetection

Did something change with Angular 8 to 11 to cause Child to Parent communication to throw ExpressionChangedAfterItHasBeenCheckedError


I figured I should learn my techniques so I was adding to my Angular 11.x application.

Getting this error ( which I did see other stackoverflow questions on and blogs about it but those issues seem to be more complicated things going on).

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Hello from the Child'.

Parent HTML :

 <app-child></app-child>
 Message from child : {{ ParentGettingChildMessage }}

Parent Component code:

import { Component, ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from 'src/app/child/child.component';
@Component({.... })

export class ParentComponent implements AfterViewInit {

   @ViewChild(ChildComponent) child;

   ParentGettingChildMessage: string;

   constructor() { }

   ngAfterViewInit(){
      this.ParentGettingChildMessage = this.child.message;
   }

}

Child Component:

export classs ChildComponent implements OnInit {
    message = "Hello from the Child";
 .....
}
 

The blog that I found it on seems to be written with Angular 8 in 2020 - It seems reasonable way to communicate from Child to Parent for reference > www . thirdrocktechkno . com/blog/how-angular-components-communicate/

Why am I getting this error?


Solution

  • There is a simple fix for this. This only happens when angular is in dev mode. It usually shows this error when angular checks values it has passed to the child component has been changed. This is an elaborative article which tells in depth how it happens, you should look at it.

    ngAfterViewInit(){
         setTimeout(() => {
           this.ParentGettingChildMessage = this.child.message;
         })
          
       }