Reputation: 2212
Created an update form, that basically is populated with information.
What I want is for the button to be disabled, until the info within the form is changed
The form group is using valuechanges to listen when info has been edited
But the form is always touched, even if I change using
this.formGroup.markAsUntouched()
The form itself does register the fact that I've set it to untouched
setFormValues(){
this.firstNameControl.setValue(user.firstName);
this.lastNameControl.setValue(user.lastName);
this.emailControl.setValue(user.email);
this.userNameControl.setValue(user.userName);
this.emailControl.setValue(user.email);
//Tried setting here this.formGroup.markAsUntouched()
}
onFormChanges() {
return this.formGroup.valueChanges
.subscribe(val => {
//Can set here but will always be untouched, as well if I use
this.formGroup.markAsUntouched()
console.log(this.count, this.formGroup.valid, this.formGroup.touched, this.formGroup.dirty)
});
}
I understand the above will always be untouched, but if I omit that, it executes twice on init and sets the form to touched, because, i suppose, the information from the db is loaded, have tried using a counter var; if counter == 2 (second iteration) of valuechanges then this.formGroup.markAsUntouched()
Which works, another thing is the html doesn't seem to register that the formgroup is disabled
<button class="btn btn-primary btn-complimentary" type="submit" [disabled]="!formGroup.touched">
Upvotes: 6
Views: 20668
Reputation: 598
You can use:
markAllAsTouched()
this.formName.markAllAsTouched();
Upvotes: 0
Reputation: 209
To set form again untouched we can simply use
this.form.markAsUntouched();
and if you want to set it to pristine
this.form.markAsPristine();
Note: We can also set a particular control of form to untouched or pristine.
Upvotes: 5
Reputation: 5036
To handle this kind of behavior in my forms, I use a combination of pristine
and valid
(use valid
only if you have some validation on your fields). I don't use touched
because you can touch an input without changing its value.
<button type="submit" [disabled]="formGroup.pristine || !formGroup.valid">
After sending the data to the server, if you want to re-disable the button, you can use the reset()
function of your formGroup
Resets the form control. This means by default:
- it is marked as pristine
- it is marked as untouched
- value is set to null
You can also reset to a specific form state by passing through a standalone value or a form state object that contains both a value and a disabled state (these are the only two properties that cannot be calculated).
Like it said, you can provide the new state of your form in the first parameter of reset()
Upvotes: 6