I want to enable the Submit button in the form only when the form input is changed.
The Submit button should be disabled when the form control values are not changed.
I tried to use the FormGroup.pristine flag for the enable / disable of the Submit button.
It works fine for enabling the button.
However, it does not get reset to true
when the value in the UI is changed back to its original value.
The component code:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-registration-form',
templateUrl: './registration-form.component.html',
styleUrls: ['./registration-form.component.scss']
})
export class RegistrationFormComponent {
public registrationForm;
public formValues = {
gender: 1,
};
constructor(private formBuilder: FormBuilder) {
this.registrationForm = formBuilder.group(this.formValues);
}
onSubmit(formData) {
console.log('Your form is submitted', formData);
this.registrationForm.reset(this.formValues);
}
}
<form class="registration-form" [formGroup]="registrationForm" (ngSubmit)="onSubmit(registrationForm.value)">
<div>
<label for="gender">Gender</label>
<select id="gender" formControlName="gender">
<option value=1>female</option>
<option value=2>male</option>
<option value=3>do not specify</option>
</select>
</div>
<input type="submit" [disabled]="registrationForm.pristine">
</form>
By default, the option "female" is selected in the select box.
When the user changes it to "male", for example, the Submit button is enabled.
Now when the user selects "female" again, the Submit button does not become disabled.
The user has to click the Submit button in order to get back the pristine status and get the button disabled.
How to reset to pristine status when the user changes back the select box value to default, without clicking the Submit button?
Angular version: 8.2.14
.
Update
Sadly angular does not seem to change form status to pristine, when the user changes UI to default values.
So we have to write code to do the data comparison and mark the form to pristine status.