[angular] Disable Input fields in reactive form

I already tried to follow the example of other answers from here and I did not succeed!

I created a reactive form (ie, dynamic) and I want to disable some fields at any given time. My form code:

this.form = this._fb.group({
  name: ['', Validators.required],
  options: this._fb.array([])
});

const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
  value: ['']
}));

my html:

<div class='row' formArrayName="options">
  <div *ngFor="let opt of form.controls.options.controls; let i=index">
    <div [formGroupName]="i">
      <select formArrayName="value">
        <option></option>
        <option>{{ opt.controls.value }}</option>
      </select>
    </div>
  </div>
</div>

I reduced the code to facilitate. I want to disable the field of type select. I tried to do the following:

form = new FormGroup({
  first: new FormControl({value: '', disabled: true}, Validators.required),
});

not working! Does anyone have a suggestion?

This question is related to angular

The answer is


I solved it by wrapping my input object with its label in a field set: The fieldset should have the disabled property binded to the boolean

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

If you want to disable first(formcontrol) then you can use below statement.

this.form.first.disable();


It is bad practice to use disable in a DOM with reactive forms. You can set this option in your FormControl, when you init the from

username: new FormControl(
  {
    value: this.modelUser.Email,
    disabled: true
  },
  [
    Validators.required,
    Validators.minLength(3),
    Validators.maxLength(99)
  ]
);

Property value is not necessary

Or you can get your form control with get('control_name')and set disable

this.userForm.get('username').disable();

while making ReactiveForm:[define properety disbaled in FormControl]

 'fieldName'= new FormControl({value:null,disabled:true})

html:

 <input type="text" aria-label="billNo" class="form-control" formControlName='fieldName'>

setTimeout(() => { emailGroup.disable(); });

Providing disabled property as true inside FormControl surely disables the input field.

this.form=this.fb.group({
  FirstName:[{value:'first name', disabled:true}],
  LastValue:['last name,[Validators.required]]
})

The above example will disable the FirstName input field.

But real problem arises when you try to access disabled field value through form like this console.log(this.form.value.FirstName); and it shows as undefined instead of printing field's actual value. So, to access disabled field's value, one must use getRawValue() method provided by Reactive Forms. i.e. console.log(this.form.getRawValue().FirstName); would print the actual value of form field and not undefined.


To make a field disable and enable of reactive form angular 2+

1.To disable

  • Add [attr.disabled]="true" to input.

<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">

To enable

export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}

Enable whole form

this.formname.enable();

Enable particular field alone

this.formname.controls.firstname.enable();

same for disable, replace enable() with disable().

This Works fine. Comment for queries.


enter image description here

lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),

Pay attention

If you are creating a form using a variable for condition and trying to change it later it will not work, i.e. the form will not change.

For example

this.isDisabled = true;
    
this.cardForm = this.fb.group({
    number: [{value: null, disabled: this.isDisabled},
});

and if you change the variable

this.isDisabled = false;

the form will not change. You should use

this.cardForm.get('number').disable();

BTW.

You should use patchValue method for changing value:

this.cardForm.patchValue({
    number: '1703'
});

The best solution is here:

https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110

Outline of solution (in case of broken link):

(1) Create a directive

import { NgControl } from '@angular/forms';

@Directive({selector: '[disableControl]'})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {}
}

(2) Use it like so

<input [formControl]="formControl" [disableControl]="condition">

(3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):

onSubmit(form) {
  const formValue = form.getRawValue() // gets form.value including disabled controls
  console.log(formValue)
}

this.form.enable()
this.form.disable()

Or formcontrol 'first'

this.form.get('first').enable()
this.form.get('first').disable()

You can set disable or enable on initial set.

 first: new FormControl({disabled: true}, Validators.required)

If to use disabled form input elements (like suggested in correct answer how to disable input) validation for them will be also disabled, take attention for that!

(And if you are using on submit button like [disabled]="!form.valid"it will exclude your field from validation)

enter image description here


You can declare a function to enable/disable all of the form control:

  toggleDisableFormControl(value: Boolean, exclude = []) {
    const state = value ? 'disable' : 'enable';
    Object.keys(this.profileForm.controls).forEach((controlName) => {
      if (!exclude.includes(controlName))
        this.profileForm.controls[controlName][state]();
    });
  }

and use it like this

this.toggleDisableFormControl(true, ['email']);
// disbale all field but email

This worked for me: this.form.get('first').disable({onlySelf: true});


A more general approach would be.

// Variable/Flag declare
public formDisabled = false;

// Form init
this.form = new FormGroup({
  name: new FormControl({value: '', disabled: this.formDisabled}, 
    Validators.required),
 });

// Enable/disable form control
public toggleFormState() {
    this.formDisabled = !this.formDisabled;
    const state = this.formDisabled ? 'disable' : 'enable';

    Object.keys(this.form.controls).forEach((controlName) => {
        this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'
    });
}

I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).

In my case I had to reset my form before reloading:

this.form = undefined; this.router.navigate([path]);


The disabling FormControl prevents it to be present in a form while saving. You can just set it the readonly property.

And you can achieve it this way :

HTML :

<select formArrayName="value" [readonly] = "disableSelect">

TS :

this.disbaleSelect = true;

Details here