How can you dynamically set disabled for Angular reactive form?

LanceM picture LanceM · May 31, 2017 · Viewed 11k times · Source

I have an Angular 4.10 application that is using the Kendo Angular Grid control. I am using External Editing. I have created the FormGroup as below:

        this.editForm = new FormGroup({
        'Id': new FormControl({ value: 0, disabled: true }),
        'Name': new FormControl("", Validators.compose([Validators.required, Validators.maxLength(30)])),
        'BlindName': new FormControl({ value: "" }, Validators.compose([Validators.required, Validators.maxLength(30)])),
        'UnitText': new FormControl(0),
        'IsFromBsp': new FormControl(true),
        'Disabled': new FormControl(false),
        'SortOrder': new FormControl(0, Validators.compose([Validators.required, Validators.pattern('\\d')]))
    });

What I would like to do is set the disabled state for the field BlindName based on the value IsFromBsp. Something like:

'BlindName': new FormControl({ value: "", disabled: this.IsFromBsp }, Validators.compose([Validators.required, Validators.maxLength(30)])),

Is there a way to achieve this? Please let me know. Thanks

Answer

AJT82 picture AJT82 · May 31, 2017

I assume you want to disable input field if IsFromBsp is true. If this is needed only initially, you can run a function after building the form:

check() {
  if(this.editForm.get('IsFromBsp').value == true) {
    this.editForm.get('BlindName').disable()
  }
}

If this value changes, you have to call this function again on some change event, either with (change) or then use valueChanges to watch for changes in the form values, where if the value is something else than true you can do this.editForm.get('BlindName').enable() to enable it again. This works with "regular" reactive form, hopefully also with Kendo.