0

I'm new to Angular, I saw some code from my textbook as below:

...
@ContentChildren(PaCellColor)
 contentChildren: QueryList<PaCellColor>;

ngAfterContentInit() {
   this.contentChildren.changes.subscribe(() => {
      setTimeout(() => this.updateContentChildren(this.modelProperty), 0);
 });
}

I don't understand why we needs to use setTimeout function?

1 Answers1

0

here setTimeOut used for not getting error Expression has changed after it was checked. Previous value: 'ngClass: show'. Current value: 'ngClass: hide'.

This is called change detection. Angular internally calls change Detection strategy of property, when we changed property of child component in parent component, using @contentChild.

When Angular runs validation stage it detects that there's a pending update to the properties and throws the error, So, here setTimeOut used to run some code asynchronously to avoid change detection strategy error.

or you can tell angular about change detection this.cdref.detectChanges();

for reference this is stack overflow post is useful for you.. Change Detection Strategy

Developer
  • 3,309
  • 2
  • 19
  • 23