[英]Run Angular change detection only once and stop detecting changes for that component
我只需要在加载组件或路由发生变化时检测一次角度变化,然后我想停止检测变化。
实际上我需要根据用户角色显示和隐藏功能。 所以我在一个 html 模板中有很多*ngIf
但我只需要在模板第一次加载时检查一次*ngIf
条件,然后停止检测更改,因为它影响性能。
我希望页面在单次更改检测后像静态一样。
例如 :
<li *ngIf="doesHavePermission('templateName')">
</li>
应该检查一次,但我看到的是它正在多次检查单个*ngIf
的更改,我有很多*ngIf
像这样:
我在这个角度文档https://angular.io/api/core/ChangeDetectorRef 中找到了markForCheck()
和detach()
。
但他们正在做的是他们要么允许所有更改检测,要么根本不允许,
而且我只需要检测一次更改并在此之后停止。
我们可以在角度上进行单次时间变化检测吗?
或者有更好的方法来处理场景吗?
当您在*ngIf
使用函数调用时,每次发生更改检测时 angular 都会调用此函数。 这个 changeDetection 是在你的组件外部还是内部触发都没有关系,但是 angular 在调用这个函数之前无法知道函数的返回值是否已经改变。
因此,通常在*ngIf
中使用函数调用并不是一个好方法。
备择方案:
在组件中使用普通属性:
instead of
<div *ngIf="checkCondition()"></div>
use this
<div *ngIf="condition"></div>
@Component(...)
class MyComponent {
condition= false;
checkCondition() {
if(something) {
this.condition = true;
}
}
}
使用这种方法,您可以在条件发生变化时更好地处理并手动调用该函数。 除了使用属性,您还可以使用地图:
@Component(...)
class MyComponent{
conditions: { [key: string]: boolean }
ngOnInit() {
condition = {
template1: true,
template2: false
}
}
}
<div *ngIf="conditions['template1']"></div>
在与组合ChangeDetectionStrategy.OnPush
可以最大限度地减少changedetection作为onPush
当输入PARAMS改变才会触发变化检测。 这基本上意味着来自父项的更改检测不会触发子项的更改检测。
如果你结合这两种方法,你应该得到最小的变化检测:
@Component({
...
changeDetection: ChangeDetectionStrategy.OnPush
})
class MyComponent{
@Input() conditions: { [key: string]: boolean }
}
这是一篇可供进一步阅读的好文章: https : //medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496
您可以只使用ChangeDetectorRef
注入器的detach
方法从变更检测周期中删除当前组件。 您可以随时拨打reattach
方法或手动调用detectChanges
通过修改,使快速运行。
对我来说,这是最可靠的方式。
但请注意,它始终会关闭所有孩子的变化检测!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.