I'm working on a simple Angular 2 app and am having trouble resetting an ngForm but keeping a default value:
Expected behavior is when clicking "Reset", the input box will reset to it's default value ("Default" in this case) as well as all of the angular specific classes going back to the default (i.e. ng-untouched, ng-pristine, etc)
What I am seeing is the default value is being cleared as well, even when I explicitly set it after the form is reset
Code snippet below:
HTML:
<form (ngSubmit)="onTrainSearchClick()" novalidate #trainForm="ngForm">
<input type="text" [(ngModel)]="id" name="someId"/>
<button type="button" (click)="reset(trainForm)">Reset</button>
<button type="submit">Search</button>
</form>
TypeScript (left out the imports and @Component):
export class TrainSearchTestComponent implements OnInit {
id: string = 'DEFUALT';
constructor() { }
ngOnInit() { }
onTrainSearchClick(){ }
reset(form: NgForm){
form.resetForm();
this.id = 'DEFUALT';
}
}
Use form.reset
:
form.reset({ id: this.id });
Original answer (valid for angular@2)
You can pass a value to resetForm
which will be used as a default value for the form:
form.resetForm({ id: this.id });
(of course if your form is a FormGroup
and it has a control with the name id
which should have a default value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With