I have a component with a template driven form, which I have an object myObj that gets the values from the form's fields. The component looks something like:
export class a {
myObj:any;
..
..
initiateObj():void {
this.myObj = {
x:"",
y:"",
z:[],
xy: []
};
}
..
..
reset():void {
this.initiateObj();
}
ngOnInit() {
this.initiateObj();
}
The view looks something like:
<form #myForm="ngForm">
<input ... [(ngModel)]="myObj.x" #myInput="ngModel" />
<input ... [(ngModel)]="myObj.y" #myInput1="ngModel" />
<select ... [(ngModel)]="myObj.z">
</select>
..
..
<button .... (click)="submit()">
<button .... (click)="reset()">
</form>
when the component initiates the values in the console of myObj are:
x:" ",
y:" ",
z:[],
etc.
However, when I fill the form - even if I not fill the form, just click the reset button, the values of myObj in the console will be:
x: null,
y: null,
z:[null]
..
which causes an error when I need to use myObj again (when I need to use the form again).
When the component initiates for the first time, the values are Ok. But once I click the reset button, the values become null.
I tried to use in the view one way binding - [ngModel] instead of [(ngModel)], and then when I click reset it's Ok, but then myObj will not get the values from the form - because it's one way binding. So I have to use two way bindings. But then when I click on reset the values of the object become null.
I also tried something like:
<button .... (click)="myForm.reset(); reset();"
or in the component with ViewChild to do this.myForm.reset()
But it didn't resolve the issue.
Is there a way to unbind the object from the [(ngModel)] when reset?
Or any other way to solve this issue ? (and still use two way bindings [(ngModel)] )
It's a form that should be used few times before leave / initiate again the component.
Please advise.
Thanks