Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressionChangedAfterItHasBeenCheck Error in using Angular Component

I have created a date-picker component in my Angular app. When i use it inside *ngIf, I got error ExpressionChangedAfterItHasBeenCheck. Let,I am using two component P and C. P as parent Input field.

<INPUT [p]=" '' ">

C as child drop-down appends after INPUT.

<DIV>
// drop-down code
</DIV>

When P is created dynamically inside *ngIf, I got such error ExpressionChangedAfterItHasBeenCheck.

like image 283
Ravi Kant Avatar asked Dec 21 '17 05:12

Ravi Kant


1 Answers

A running Angular application is a tree of components. During change detection Angular performs checks for each component which consists of the following operations performed in the specified order:

  1. update bound properties for all child components/directives
  2. call ngOnInit, OnChanges and ngDoCheck lifecycle hooks on all child components/directives
  3. update DOM for the current component
  4. run change detection for a child component
  5. call ngAfterViewInit lifecycle hook for all child components/directives

After each operation Angular remembers what values it used to perform an operation. They are stored in the oldValues property of the component view. After the checks have been done for all components Angular.

So at the end, We need to make it synchronous for Angular and to solve it we use setTimeout inside lifecycle hooks.

ngOnInit() {
    setTimeout(() => {
    // Your Code
    });
}
ngAfterViewInit() {
    setTimeout(() => {
    // Your Code
    });
}
like image 58
mukund patel Avatar answered Nov 15 '22 07:11

mukund patel