Angular 4 基于视图的变化 [英] Angular 4 Changes based on view

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

问题描述

我有一个 div 就像

I have a div which is like

 <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 中计算它们.

这当然给了我这个错误:

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?

(如果我根据组件视图计算变量,我需要 ngAfterViewChecked --> 我需要再次detectChanged,如果我每次都进行 ChangeDetectorRef.detectChanges() --> 我将进入一个循环.--> 我需要一个条件来阻止它.这感觉很糟糕而且是错误的.

(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天全站免登陆