Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What actually triggers ControlValueAccessor's setDisabledState function?

I'm trying to figure out how to implement the setDisabledState function that is a part of the ControlValueAccessor interface, but I can't figure out how to actually trigger the function from outside of the component itself.

Within the component I have

control = new FormControl();

setDisabledState(isDisabled: boolean): void {
    this._renderer.setProperty(this.formField.nativeElement, 'disabled', isDisabled);
  }

This sets my disabled styling fine if I do the below inside the NgOnInit of my component. But I want to be able to control the disabled state of my component through property binding.

this.tenantListFormControl.disable();

However, nothing actually triggers the function.

I've tried

<app-custom-control [attr.disabled]="true"></app-custom-control>
<app-custom-control disabled></app-custom-control>
<app-custom-control [disabled]="true"></app-custom-control> 

The last one isn't even valid as "Property disabled is not provided by any applicable directives etc..." as I don't have @Input() disabled anywhere on the component. Which wouldn't help anyway because what am I supposed to do with that once I've set it, I can't subscribe to it and trigger the setDisabledState function that way as it's not an observable.

How do I actually trigger this function and disable my component?

like image 769
Jake12342134 Avatar asked Aug 09 '26 15:08

Jake12342134


1 Answers

Jake, to disable a FormControl (If you're using reactive Forms) you need use the method disable() -or create as disabled- so using [disable] or [attr.disable] don't call to your function setDisabledState. you can think in a @Input like

@Input() set disabled(value)
{
   this.setDisabledState(value)
}

But this "break" the Angular Reactive Form. If you use [disabled]="true" in a Reactive Form you can see and advertisment: "It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true when you set up this control in your component class, the disabled attribute will actually be set in the DOM for you. We recommend using this approach to avoid 'changed after checked' errors."

The most closer "Angular way" to disable a FormControl is using a directive, see e.g. this SO

like image 158
Eliseo Avatar answered Aug 12 '26 07:08

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!