Angular ChangeDetectionStrategy.OnPush会中断ControlValueAccessor的禁用状态

Angular ChangeDetectionStrategy.OnPush会中断ControlValueAccessor的禁用状态,angular,typescript,angular-components,angular-forms,Angular,Typescript,Angular Components,Angular Forms,在Angular应用程序中,我通过实现接口创建了一个自定义表单元素 因此,在我的组件中,我正确地实现了该接口的所有方法,包括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. *

在Angular应用程序中,我通过实现接口创建了一个自定义表单元素

因此,在我的组件中,我正确地实现了该接口的所有方法,包括
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;
}
一切正常

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


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

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

我们需要在我们的组件中注入:

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
}

只有当我们谈论父/子组件通信时,OnPush才有意义。当子级具有changeDetection:ChangeDetectionStrategy.OnPush设置且父级将对象作为输入传递给子级时


如果要创建具有自己状态的被动自定义表单控件。最好避免使用onPush。如果您想使用,可以使用cdr.markforCheck()手动调用更改检测。

谢谢您的建议,但是在我的例子中,我只是试图解决库的现有组件上的一个问题。因此,更改更改检测策略不是我的职责: