我通过控制访问来使用属性来检查是否应启用或禁用字段。
所以我有这样的东西:
<input matInput type="text" #name="ngModel" name="application.name" [ngModel]="application?.name" (ngModelChange)="application.name=$event"
placeholder="Nom de l'application" required [disabled]="isDisabled([permissions.applications.any.update, permissions.applications.own.update], 'name')"[appUnique]="application" [listElem]="applications" key="name" maxlength="255">
当显示输入时,isDisabled
函数会被调用数百次,并且表单上的每个操作都会触发 12 或 32 次额外调用。
这会导致我的浏览器卡住。
知道为什么会发生这种行为吗?是ZoneJS造成的吗?
如何才能只调用一个函数?
编辑:指令实现
/**
* Check if the component should be disabled
*/
@Directive({
selector: "[appIsDisabled]"
})
export class IsDisabledDirective implements OnInit {
// Listof permission to check
@Input("appIsDisabled") permissions: PermissionInterface[];
// The resource id to be access
@Input() resourceId: number;
// The resource type to be access
@Input() resourceType: string;
// Attribute to be check(eg: name, firstname... for a user resource)
@Input() attribute: string;
constructor(private authService: AuthService, private el: ElementRef, private utilsService: UtilsService, private renderer: Renderer2) {
}
ngOnInit() {
if (!this.authService.hasPermission(this.permissions, this.resourceId, this.resourceType, this.attribute)) {
this.renderer.setAttribute(this.el.nativeElement, "disabled", "disabled");
}
}
}
最佳答案
您最好不要将属性绑定(bind)到方法,以避免过于频繁地检查状态。
以下是我的建议:
- 使用RxJS来跟踪更改。
- 尝试检测您的 permissions.applications.any.update 更改并将其包装到 Observable 中。您可以从组件中的
ngOnInit
Hook 订阅此内容。
- 尝试检测您的 permissions.applications.any.update 更改并将其包装到 Observable 中。您可以从组件中的
- 使用Pure Pipe来检测变化。
- 尝试将
isDisabled
方法移至纯管道组件。
- 尝试将
- 使用setInterval定期检查状态变化。
关于javascript - 为什么在计算函数时输入属性被调用数百次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50720870/