I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().
For illustration, that's how I made it, including the fields initialization:
ngOnInit() {
// initializing the form model here
this.createForm();
}
createForm() {
let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too
this.userForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
city: new FormControl(''),
email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
});
this.initializeFormValues();
}
initializeFormValues() {
const people = {
name: '',
city: 'Rio de Janeiro', // Only for demonstration
email: ''
};
(<FormGroup>this.userForm).setValue(people, { onlySelf: true });
}
resetForm() {
this.createForm();
this.submitted = false;
}
I added a button to the form for a smart reset (with the fields initialization):
In the HTML file (or inline template):
<button type="button" [disabled]="userForm.pristine" (click)="resetForm()">Reset</button>
After loading the form at first time or after clicking the reset button we have the following status:
FORM pristine: true
FORM valid: false (because I have required a field)
FORM submitted: false
Name pristine: true
City pristine: true
Email pristine: true
And all the field initializations that a simple form.reset() doesn't make for us! :-)