In an Angular Form, we may sometimes be required to disable some of the form controls based on complex logic. When we make a form control is disabled, it is not considered as the value during submission of the forms.
The form control values are only fetched from controls that are enabled on the time of submission, whereas the disabled form control values are simply ignored.
In this quick tutorial, we’ll create a simple Angular form and get the value of disabled form control while submitting it.
Create a Simple Form
In the App, component add the following simple form with First Name and Last Name as shown below:
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
<button type="submit">Submit</button>
</form>
<button (click)="disableLastName()">Disable LastName</button>
<button (click)="enableLastName()">Enable LastName</button>
It is having two buttons to Enable/ Disable the Last name control.
Update the App component class with the following code:
// app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
profileForm = this.fb.group({
firstName: [''],
lastName: ['']
});
constructor(private fb: FormBuilder) { }
ngOnInit() { }
onSubmit() {
console.log(this.profileForm.value);
}
disableLastName() {
this.profileForm.controls.lastName.disable();
}
enableLastName() {
this.profileForm.controls.lastName.enable();
}
}
Now, Run the application by hitting “ng serve --open
”
Without Disabled Lastname
Now if click on the Submit button, you will see the firstName and lastName values in the console window, given by the
this.profileForm.value
With Disabled LastName
Now click on the “Disable LastName” button to disable the control. Then click submit to notice that there will be no value for lastName.
Solution To Get Disabled Form Control Values
You need to update the Submit method as shown below:
onSubmit() {
console.log('Before', this.profileForm.value);
for (const prop in this.profileForm.controls) {
this.profileForm.value[prop] = this.profileForm.controls[prop].value;
}
console.log('After', this.profileForm.value);
}
Here, we are getting values from each control using controls inside the for loop for props then updating the values object which was missing the disabled props
We discussed how to easily overcome the situation where we don’t get the value of Form control if its disabled but we want to fetch its value and pass it to the Form payload.