Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked

Tags:

angular

What's wrong? Getting the following error in console:

AboutComponent.html:1 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: undefined'. Current value: 'null: [object Object]'.

import { AfterViewInit, Component} from '@angular/core';

export class Test {

}

@Component({
  selector: 'app-about',
  template: `
    {{asd}}
  `
})
export class AboutComponent implements AfterViewInit {

  asd: Test;

  ngAfterViewInit(): void {
    this.asd = new Test();
  }
}
like image 635
Denis Kildishev Avatar asked Dec 13 '18 17:12

Denis Kildishev


2 Answers

You can also force change detection after you make a change within ngAfterViewInit() as such:

import { AfterViewInit, Component, ChangeDetectorRef} from '@angular/core';

export class Test {

}

@Component({
  selector: 'app-about',
  template: `
    {{asd}}
  `
})
export class AboutComponent implements AfterViewInit {

  asd: Test;

  constructor(
    private cdRef: ChangeDetectorRef   
  ) { }

  ngAfterViewInit(): void {
    this.asd = new Test();
    this.cdRef.detectChanges(); 
  }
}  
like image 134
Jackson Vaughan Avatar answered Sep 22 '22 08:09

Jackson Vaughan


Some Lifecycle hooks are called before the rendering part when Angular processes bindings and some are called after that

Ref:https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10

The error is due to the Angular call this ngAfterViewInit method once all the binding processed. To get rid this error you can do the following

Move your code inside ngOnInit lifecycle hook

ngOnInit() {
    this.data = new Test()
}

Or

Wrap your code inside setTimeout()

 ngAfterViewInit() {
    setTimeout(()=>this.data = new Test(),0)
  }

Great Article about the same issue: https://blog.angular-university.io/angular-debugging/

like image 37
Chellappan வ Avatar answered Sep 18 '22 08:09

Chellappan வ