patchValue to set value and disable the field
Asked Answered
T

2

5

I'm pushing a FormArray with some values, and i need to dynamically set disabled property in certain fields after i've loaded a list. My question is: IS there a way to set the value and set the disabled property using only patchValue?

I've tried something like this.rowArray.controls[index].patchvalue({format: "NUMBER", disabled:true}) but it doesn't seem to work.

  this.rowList.forEach((el, index) => {
              this.rowArray.push(
                this.fb.group(
                  {
                    name: new FormControl(el.name, [
                      Validators.required,
                      Validators.maxLength(30),
                      Validators.pattern(this.BAN_SPECIAL_BUT_UNDERSCORE)
                    ]),
                    source: new FormControl(el.source, Validators.required)
.....

and after that

    if (this.rowArray.controls[index].get("source").value === "CSV") {
                this.rowArray.controls[index].patchValue({
                  format: "NUMBER",
                  disabled: true
                });
              }

rowList is my matrix that comes from backEnd.

Telemeter answered 4/7, 2019 at 7:46 Comment(0)
P
13

You can dynamically set your FormControl to be disabled by using the disable() method.

As stated on the documentation, patchValue() will not work, as it is only used for setting the values (and not the state) of your FormControl.

Patches the value of the FormGroup. It accepts an object with control names as keys, and does its best to match the values to the correct controls in the group.

this.rowArray.controls[index].get('source').disable();
Patently answered 4/7, 2019 at 7:55 Comment(1)
Worked for me, but the value field wasn't populated, so I had do re-enable it jsut before my POST method, and then re-launch my enable/disable method.Telemeter
M
1

Some examples can be found in the documentation.

Use the same way to disable controls when initializing them.

this.form = new FormGroup({
     format: new FormControl(),
     otherControl: new FormControl({ value: "CustomValue", disabled: true }) //"otherControl" initializes disabled
})
this.form.patchValue({
   format: { value: "CustomValue", disabled: true },  //Disable control by pathValue      
})

Same applies when resetting.

form.reset({
  format: {value: 'customValue', disabled: true}, //Disable control by reset
  otherControl: 'last'
});
Meistersinger answered 29/3, 2023 at 23:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.