Angular2 Reactive Forms - dynamically disable form control from a condition

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 is not included, although at some point this.activeCategory becomes a "document".

How to fix it?

+14
angular angular2-forms
source share
3 answers

Since I don’t know how you manipulate activeCategory (maybe this is also FormControl ?), I suggest the following approach:

You can use (change) to detect when this.activeCategory has changed, as shown below:

1 - If you are using ngModel :

 <input type="text" [(ngModel)]="activeCategory" (change)="checkValue($event)"> 

2 - If it is a FormControl :

 <input type="text" formControlName="activeCategory" (change)="checkValue($event)"> 

So, in the component, you can control the docType control using the disable/enable methods:

 checkValue(event: Event) { const ctrl = this.activityForm.get('docType'); if (event.value === 'document') { ctrl.enable(); } else { ctrl.disable(); } } 
+32
source share

You must handle the selected elements differently than other HTML elements. You will have to reset when changing this.activeCategory .

More or less like this:

this.activityForm.controls['docType'].reset({ value: '2', disabled: false });

Of course, you probably want to use the current value, not the hard-coded '2' .

The same can be disabled if such a need arises (and, probably, it arises).

this.activityForm.controls['docType'].reset({ value: '2', disabled: true });

More information on reset control form reset .

+7
source share

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

0
source share

All Articles