简体   繁体   English

模板渲染后的角度变化检测

[英]Angular change detection after template render

So I'm looping over a list of items in my html and setting a calling a function to return true or false so that I can apply respective classes, also I'm setting a variable if any of the item gets matched in the list. 因此,我遍历了html中的项目列表,并设置了一个调用函数以返回true或false,以便我可以应用相应的类,并且如果列表中有任何项目匹配,我也将设置一个变量。 I'm using this variable for another element as *ngIf. 我将此变量用于另一个元素* ngIf。 Now initially, before the template loads, this variable is false. 现在,最初,在模板加载之前,此变量为false。 After that the component initializes and the html renders. 之后,组件初始化并呈现html。 Now where I have a looping of list of items I'm calling a function over there, it is setting that variable as true but the element that is conditioned with ngIf is not getting visible. 现在,在这里有一个我要在其中调用函数的项目列表循环时,它将该变量设置为true,但是以ngIf为条件的元素不可见。

I think it's because when the component is fully initialized the variable value is false and then when the html renders the variable's value is changed to true. 我认为这是因为当组件完全初始化时,变量值是false,然后在html呈现时,变量的值更改为true。 But this change is not detected by angular as it has already rendered that element and also didn't get any change event to watch for the variables. 但是,此角度变化不会被角度检测到,因为它已经渲染了该元素,并且也没有任何变化事件来监视变量。

Here is my html 这是我的html

<div *ngIf="someVariable">
some content
</div>

<div *ngFor="let item of items">
  <div [ngClass]="{isItemMatched(item) : my-class}"></div>
</div>

Here is my component 这是我的组件

somevariable = false

isItemMatched(item) {
  forLoop() {
   if(true) {
      this.someVariable = true
      return true
     }
   }
}

Is there any way to so that we can trigger angular change detection like in a click event or soemthing so that angular can update the view? 有什么方法可以使我们可以触发角度变化检测,例如在单击事件或发出声音时,以便角度可以更新视图?

First of all, you are using ngClass in wrong way. 首先,您以错误的方式使用ngClass。 The left side of ngClass should be the class name and right side should be boolean value. ngClass的左侧应为类名,右侧应为布尔值。 Eg. 例如。

<div [ngClass]="{'my-class' : isItemMatched(item)}"></div>

To update the view when value changes, you can use ChangeDetectorRef Inject this class in your constructor and then use the method markForCheck(). 要在值更改时更新视图,可以使用ChangeDetectorRef将此类注入构造函数中,然后使用方法markForCheck()。 This method updates the view. 此方法更新视图。

constructor(private cdr: ChangeDetectorRef){
}
someMethod(){
  this.someVariable = true; //Value changed.
  this.cdr.markForCheck(); //View updated.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM