问题
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