Angular2 Reactive Forms - Disable form control dynamically from condition

Viewed 66758

I have a select control that I want to disable dynamically based on a condition:

this.activityForm = this.formBuilder.group({
  docType: [{ value: '2', disabled: this.activeCategory != 'document' }, Validators.required]
});

However, docType doesn't become enabled even though at some point this.activeCategory becomes 'document'.

How do I fix this?

5 Answers

from .ts file you can add keys to yours from controls, and there you add the item disabled:true (desactivate form item) or false (activate form item)

.ts

public form_name=new FormGroup({

              series: new FormControl({value: '', disabled: true}),
              inten: new FormControl({value: '', disabled: true}),
              rep: new FormControl({value: '', disabled: true}),
              rest: new FormControl({value: '', disabled: false}),
              observation: new FormControl({value: '', disabled: false}),



  });

.html

<form  [formGroup]="form_name" >

                                          <label for="series"  >Series</label>
                                           <input type="text" formControlName="series" >

                                          <label for="inten"  >Inten</label>
                                           <input type="text" formControlName="inten" >

                                          <label for="rep"  >Rep</label>
                                           <input type="text" formControlName="rep" >

                                           <label for="rest"  >rest</label>
                                            <textarea formControlName="rest" rows="3" cols="30" ></textarea>


                    </form>

this.activityForm.controls['docType'].disable();

you can use ternary operator here to disable form control conditionally.

this.activityForm = this.formBuilder.group({
docType: [{ value: '2', disabled: this.activeCategory != 'document' ? true : false }, Validators.required]
});


Related