Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Reactive Forms - Disable form control dynamically from 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 doesn't become enabled even though at some point this.activeCategory becomes 'document'.

How do I fix this?

like image 567
franco Avatar asked May 15 '17 23:05

franco


People also ask

How do I turn off form control and keep value?

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. Example: form = new FormGroup({ first: new FormControl({value: 'Nancy', disabled: true}, Validators.

How do I disable FormControl in Angular 7 dynamically?

We can use disable() and enable() method of FormControl . We can also call disable/enable function at runtime by using control[action]() method of FormControl . We need to pass action as 'disable' or 'enable'. We can also use [disabled]="true" binding to disable a form control.


1 Answers

Since I don't know how you're manipulating activeCategory (maybe it's also a FormControl?), I'll suggest the following approach:

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

1 - If you're using ngModel:

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

2 - If it's a FormControl:

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

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

checkValue(event: Event) {
  const ctrl = this.activityForm.get('docType');

  if (event.value === 'document') {
    ctrl.enable();
  } else {
    ctrl.disable();
  }
}
like image 86
developer033 Avatar answered Sep 22 '22 09:09

developer033