Reputation: 1328
In my Angular 2 component I'm using a Formgroup
with 18 AbstractControl
s. Users can edit their profile, which is loaded from the database.
I want to add a Reset
-button to reset the form to it's original state (obviously). Using this.form.reset()
however clears all fields. I can reset a specific AbstractControl
within the FormGroup
by calling reset({firstname: 'Jack'});
.
Is it possible to change the state of FormGroup
it resets to?
Upvotes: 2
Views: 3078
Reputation: 73387
If you build (or have built) your form as such, that the profile
object matches the properties in your form group, you can just call:
this.profileForm.reset(this.profile);
for example:
profile = {firstname: 'first name'};
// ...
this.profileForm = this.formBuilder.group({
firstname: [this.profile.firstname],
});
// ...
this.profileForm.reset(this.profile)
With template:
<form [formGroup]="profileForm">
<input formControlName="firstname" />
</form>
Upvotes: 4
Reputation: 5731
Create a form initialize function, and call it after you reset
component.html
<form [formGroup]="profileForm">
<input formControlName="firstname" class="form-control">
<button class="btn" type="submit">Submit </button>
<button class="btn" type="button" (click)="onReset()">Reset </button>
</form>
Component.ts
profileForm: FormGroup;
profile = {
firstname: 'name'
}
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.initForm();
}
initForm() {
this.profileForm = this.formBuilder.group({
firstname: [this.profile.firstname, Validators.required]
});
}
onReset() {
this.profileForm.reset();
this.initForm();
}
Upvotes: 1