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
.
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.
You can use markAsPristine method to set pristine status true, when the data changes back to defaultValue like this:
ngOnInit() {
const defaultValue = this.registrationForm.value;
this.registrationForm.valueChanges
.pipe(debounceTime(200))
.subscribe(value => {
if (JSON.stringify(defaultValue) == JSON.stringify(value)) {
this.registrationForm.markAsPristine();
}
});
}
You can make one method that returns true or false for disabling the submit button if nothing is changed.
Assuming you have some object that is used for storing the inputs of the form.
Refer the below code for the function:
oldObj = _.cloneDeep(this.obj)
dataChanged(){
return !_.isEqual(this.oldObj, this.obj)
}
and in the html add the below line
<input type="submit" [disabled]="!hasChanged()">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With