angular icon indicating copy to clipboard operation
angular copied to clipboard

Allow setting enabled/disabled state of AbstractControl using a boolean value

Open moniuch opened this issue 1 year ago • 1 comments

Which @angular/* package(s) are relevant/related to the feature request?

No response

Description

Currently, in order to disable or enable an AbstractControl depending on another control's value or state, one has to use very verbose explicit code using both if/else branches of a condition:

.subscribe(value => {
  if(valueMeetsCondition(value)){
    this.ctrl.enable()
  } else {
    this.ctrl.disable()
  }
});

or its ternary equivalent.

It would simplify the code if we could say this instead:

.subscribe(value => this.ctrl.setEnabledState(valueMeetsCondition(value)));

Proposed solution

In AbstractControl API, add a pair of methods that accept a boolean value:

  • setDisabledState
setDisabledState(isDisabled: boolean, opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void
  • setEnabledState
setEnabledState(isEnabled: boolean, opts: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

I think it's important to have a pair of companions, just like we have valid/invalid, enabled/disabled property pairs on AbstractControl for the sake of coding convenience.

It would allow developers for a smoother migration and cleaner code without the need of negating the conditions in their existing code.

Alternatives considered

Workarounds? Described above which I want to stop using. Alternative solutions? Can't think of any.

moniuch avatar Oct 29 '22 13:10 moniuch