Expression has changed after it was checked in angular 9

。_饼干妹妹 提交于 2021-02-11 15:10:42

问题


I am working on Angular 9 and I have encountered an error. Please help me.

HTML:

<div *ngFor="let item of users">
  <p>{{ countFalse(item.userId) }}</p>
</div>

TS:

interface IUser {
  userId: number;
  name: string;
  act: IAct[];
}

interface IAct {
  actId: number;
  avtive: boolean;
  ...
}

users: IUser[] = [];

countFalse(id): number {
  const index = this.users.findindex((u) => u.userId == userId);
  const a = this.users[index].act.length;
  return a;
}

console:


回答1:


You need to reimplement your component. Calling functions directly in the template is not a good practice. This causes performance and change detection issues (like in this particular case).

Looking at your code looks like you have an array of users. You are then passing the ID of the user to the function, which then iterates through the array, finds the user by ID, and then returns the act.length property. All of this is driven from the template, and if your array has dozens or hundreds of items, it's a very expensive operation, with the function being called over and over in a short period of time as the list (div) in the HTML is being rendered.

A better approach will be to prepare your data before it needs to be rendered. In the onInit(), create a new array with objects and all the properties you need, and then loop through that in the template instead.

The Actual Error

Now for the actual error, it comes down to change detection. There are multiple causes, and different solutions depending on the specific case. These two articles go through this error in great detail, and provide solutions:

Article 1 Article 2

Some of the solutions include (but not limited to):

  • Manually triggering change detection
  • Refactoring your code to use RxJs
  • Refactoring your code not to call functions in the template


来源:https://stackoverflow.com/questions/65129121/expression-has-changed-after-it-was-checked-in-angular-9

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!