gpt4 book ai didi

angular - ChangeDetectionStrategy.OnPush 打破了 ControlValueAccessor 的禁用状态

转载 作者:行者123 更新时间:2023-12-03 21:22:38 25 4
gpt4 key购买 nike

在我的 Angular 应用程序中,我通过实现 ControlValueAccessor 创建了一个自定义表单元素。界面。

因此,在我的组件中,我正确实现了该接口(interface)的所有方法,包括 setDisabledState :

/**
* This function is called when the control status changes to or from "disabled".
* Depending on the value, it will enable or disable the appropriate DOM element.
*
* @param isDisabled
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}

一切正常。

问题是当我更改 ChangeDetectionStrategy我的组件将其设置为 OnPush .

通过这样做,我的组件的启用/禁用功能被破坏了。

最佳答案

该问题可以通过手动触发更改检测来解决。

我们需要注入(inject) ChangeDetectorRef进入我们的组件:

import {  ChangeDetectorRef } from '@angular/core';

// ...

constructor(
private cd: ChangeDetectorRef,
) { }

然后在启用/禁用状态更改时使用它手动触发更改检测:
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.cd.markForCheck(); // this will manually trigger the change detection
}

关于angular - ChangeDetectionStrategy.OnPush 打破了 ControlValueAccessor 的禁用状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51963831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com