I have a form that is pulled up multiple times. I need to be able to reset the submitted flag on the form to false each time it comes up to remove any possible error messages that might have been left over from the last time.
The only way I've found to set the submitted flag back to false is to use the ngForm.resetForm(model)
method.
This works well enough, except that it doesn't ngModel bind to any objects that are nested within the top level model.
Given the following object:
model: {
firstName: 'John',
contact: {
lastName: 'Smith'
}
}
and the following inputs:
<input type='text' name='firstName' [(ngModel)]='model.firstName' />
<input type='text' name='lastName' [(ngModel)]='model.contact.lastName' />
The first time the form loads, everything appears correctly.
However, if you submit the form and then call this.myForm.resetForm(this.model)
, it won't bind model.contact.lastName
. It does bind model.firstName
just fine.
I have included a plunkr that illustrates the problem here.
Is there any way to reset the submitted flag outside of resetForm? Or can someone explain why the model.contact.lastName
field is not binding correctly when resetForm is called?
When working with forms, it is important to remember that it has its own model that represents the form and the controls on the form.
When using reactive forms, we create this "model" with the FormBuilder.
When using template-driven forms, this "model" is created for us automatically based on the HTML elements with the name
attribute.
If you look at the generated model, you'll see that the model properties are firstName
and lastName
as per the name
attribute.
Data Model: { "firstName": "John", "contact": { "lastName": "Smith" } }
Form's Model: { "firstName": "John", "lastName": "Smith" }
That's why it can't find the info ... because its internal form model does NOT match your data model.
Try adding this to your plunker:
{{myForm.value | json}}<br/>
And you will see the generated form's model.
You can achieve nesting using a form group, like this:
<input type='text' name='firstName' [(ngModel)]='model.firstName' /><br />
<div ngModelGroup="contact">
<input type='text' name='lastName' [(ngModel)]='model.contact.lastName' /><br />
</div>
<br />
The resulting form model then matches your data model:
Data Model: { "firstName": "George", "contact": { "lastName": "Washington" } }
Form's Model: { "firstName": "George", "contact": { "lastName": "Washington" } }
Here is the updated plunker: https://plnkr.co/edit/AqLxE7kJsCAVIOJHBJtt?p=preview