In my Angular app, I've created a custom form element by implementing the ControlValueAccessor interface.
So in my component I correctly implement all methods of that interface, including 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;
}
Everything works fine.
The problem is when I change the ChangeDetectionStrategy of my component setting it to OnPush
.
By doing that, the enable/disable functionality of my component is broken.
The problem can be solved by manually triggering the change detection.
We need to inject the ChangeDetectorRef into our component:
import { ChangeDetectorRef } from '@angular/core';
// ...
constructor(
private cd: ChangeDetectorRef,
) { }
then use it to manually trigger the change detection whenever the enabled/disabled status changes:
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.cd.markForCheck(); // this will manually trigger the change detection
}