Reputation: 2674
For example I have a form below.
searchForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
})
The problem is that when I use searchForm.reset()
the initial value is set to null
and not to empty string ''
that I set as an initial value in the FormControl
.
I have tried doing the code below and it works.
The problem is that for example I have like 20 FormControl
, I will need to type it all and initialize it in .reset({firstName:'', other20properties..})
this.searchForm.reset(
{
firstName: '',
lastName: ''
}
);
Is there a way to reset the form and set all its initial value to empty string ''
.
Upvotes: 6
Views: 10050
Reputation: 1599
You just have to add {nonNullable: true}
in FormControl, please refer below code snippet
searchForm = new FormGroup({
firstName: new FormControl('', { nonNullable: true }),
lastName: new FormControl('', { nonNullable: true }),
city: new FormControl('')
})
here 'city' don't have nonNullable set to on reset the value of city will be null
Can see the demo in gif image: https://res.cloudinary.com/dtlx6i2m7/image/upload/v1728168332/personal-data/yqmhcevhqfgznxkzgaxa.gif
For more info refer official docs: https://angular.dev/guide/forms/typed-forms#nullability
Upvotes: 1
Reputation: 86800
In these type of scenarios better to wrap your form initialization into a separate method and call that method after form.reset
like this -
formInit() {
searchForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
})
}
anotherFunction() {
this.searchForm.reset();
this.formInit();
}
Upvotes: 9