Angular 4基于视图的更改 [英] Angular 4 Changes based on view

查看:99
本文介绍了Angular 4基于视图的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

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

isActive和topVar是基于视图计算的(例如,内容溢出并且内容是动态的).

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

所以我在ngAfterViewChecked中计算它们.

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?

(如果我基于组件视图计算var,则需要ngAfterViewChecked->我需要再次detectChanged, 如果我每次都使ChangeDetectorRef.detectChanges()->我将进入一个循环. ->我需要一个条件来停止它.感觉很hacky和错.

(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.

推荐答案

将代码包装到setTimeout函数中.喜欢

Wrap your the code into setTimeout function. Like

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

这篇关于Angular 4基于视图的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆