Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Forms disable control in component with a data-bound value

I am disabling controls when the user is not in edit mode.

this.theForm = this.builder.group({
   name: [{ value: this.model.name, disabled: !this.isEditMode}, Validators.required],
})

When they change to edit mode I want the control to be enabled. However, it seems that once this is set it will not change then the component value changes.

This was working when I had this in the markup:

<input [disabled]="!isEditMode" type="text" formControlName="name"  />

This was causing a runtime warning suggesting that I handle it with the formControl.

This is the warning:

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.

Is there a way to bind this value when I setup the control? Do I need to loop though the controls and toggle this whenever it changes?

like image 303
Don Chambers Avatar asked Apr 30 '26 10:04

Don Chambers


1 Answers

You can subscribe to the control change and update it there, something like this (off the top of my head):

ngOnInit() {
    for (let nut of this.userSettings.nutrientData) {
      this.foodSettingsForm.controls[nut.abbr].valueChanges
          .subscribe(v => { 
              this.completeValueChange(nut.abbr, v, (mode=="edit" ? false : true));
      });
   }
}

completeValueChange(field: string, value: boolean, disable: boolean) {
   this.myForm.controls[myField]
      .setValue(({value: vale, disabled: disable}, { onlySelf: true });
}
like image 196
John Baird Avatar answered May 10 '26 17:05

John Baird



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!