Angular: *ngIf 中的函数会导致性能问题,但有什么替代方法?
Angular: function inside *ngIf causes performance issues but what is the alternative?
所以我遇到了性能问题,通过搜索网络发现它是由我在 *ngIf 中拥有的所有函数引起的。一些建议是使用管道或使用 get 访问器。我试过管道,但它不起作用,我不能使用 get 访问器作为函数 havet 参数。
有些功能很简单,有些则比较复杂。用户可以通过在数组中添加或删除内容来更改状态,因此它必须保持动态。示例函数
function inBothArrays(id, array1, array2) {
if(array1.includes(id) && array2.includes(id)){
return true
} else {
return false
}
}
我会做的是为这个工作创建一个管道。
如 Angular 文档所述
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
因此,您可能需要创建一个 "inBothArraysPipe",它将数组和项目作为输入作为单个对象进行检查,只有当您决定更改它时,其引用才会更改。
然后,您将像这样修改您的代码:
1) 把你的 *ngIf 变成
*ngIf=" checkDto | inBothArrays "
2) 在组件中将 checkDto 定义为
checkDto : {id: any, array1: any[], array2 : any[]}
3) 确保每次更改 checkDto 的引用:
- 修改数组 1
- 修改数组2
- 修改id
要更改引用,您可以输入
JSON.parse(JSON.stringify(checkDto))
或
Object.assign({}, checkDto)
所以我遇到了性能问题,通过搜索网络发现它是由我在 *ngIf 中拥有的所有函数引起的。一些建议是使用管道或使用 get 访问器。我试过管道,但它不起作用,我不能使用 get 访问器作为函数 havet 参数。
有些功能很简单,有些则比较复杂。用户可以通过在数组中添加或删除内容来更改状态,因此它必须保持动态。示例函数
function inBothArrays(id, array1, array2) {
if(array1.includes(id) && array2.includes(id)){
return true
} else {
return false
}
}
我会做的是为这个工作创建一个管道。 如 Angular 文档所述
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
因此,您可能需要创建一个 "inBothArraysPipe",它将数组和项目作为输入作为单个对象进行检查,只有当您决定更改它时,其引用才会更改。 然后,您将像这样修改您的代码:
1) 把你的 *ngIf 变成
*ngIf=" checkDto | inBothArrays "
2) 在组件中将 checkDto 定义为
checkDto : {id: any, array1: any[], array2 : any[]}
3) 确保每次更改 checkDto 的引用:
- 修改数组 1
- 修改数组2
- 修改id
要更改引用,您可以输入
JSON.parse(JSON.stringify(checkDto))
或
Object.assign({}, checkDto)