Reputation: 115
I am using Angular2+, and I have a simple ngForm, that has a reset button, and a reset to defaults button at the bottom.
I want to be able to see the default values that appear when I hit the "reset form with default values" button, when the page is loaded/initialized.
I have tried doing:
<input type="text" name="" id="name" class="form-control" required="required"
title="" name="name" [(ngModel)]="defaultValues.name" required>
Where I can set an initial value, but this component will not reset...
VS
<input type="text" name="" id="name" class="form-control" required="required"
title="" name="name" ngModel required>
Where I can reset this component, but not see the initial value in the text field..
Any suggestions?
Upvotes: 2
Views: 142
Reputation: 1863
You have to understand One way Binding Vs Two way data binding. Once you have used [(ngModel)] it is possible to both assign values and get values easily.
I have updated your slack
[(ngModel)]="model.name"
[(ngModel)]="model.amount"
once i updated this working now.
Here your slackbitz https://stackblitz.com/edit/angular-mpigb7
here is more reference for understanding,
https://www.c-sharpcorner.com/article/angular-one-and-two-way-data-bindings-with-examples/
https://medium.com/@milosbejda/one-way-and-two-way-bindings-in-angular-4-explained-b5ec280767ec
Upvotes: 1
Reputation: 281
Your missing the ngModel value:
[(ngModel)]="values.name"
[(ngModel)]="values.amount"
For setting the defaultValues you can override the property with something like this:
values: any;
defaultValues = {
amount: 20,
name: 'defaultName'
}
constructor() {
this.values = this.cloneDefaultValues(this.defaultValues);
}
private cloneDefaultValues(param: any) {
// JSON parse and stringify methods because js use references on complex objects
return JSON.parse(JSON.stringify(param));
}
resetFormWithDefaultValues(){
this.values = this.cloneDefaultValues(this.defaultValues);
}
Upvotes: 2