Angular 4 Changes based on view

2019-09-16 07:36发布

问题:

I have a div which is like

 <div [ngClass]="{'active' : isActive} [ngStyle]={top: topVar } >

isActive and topVar are calculated based on the view, (like if the content overflowed, and the content is dynamic).

so I calculate them in ngAfterViewChecked.

which ofcourse gives me this error :

Expression has changed after it was checked, previous value : "undefined". current value : '636px'.

I understand what I did wrong, my question is, how to do it right?

(If I calculate the the vars based on the component view, I need ngAfterViewChecked --> I need to detectChanged again, and if I will make ChangeDetectorRef.detectChanges() everytime --> i will enter a loop. --> I need a condition to stop it. that feels hacky and wrong.

回答1:

Wrap your the code into setTimeout function. Like

ngAfterViewInit(): void {
  setTimeout({...calculation});
}