Resetting a Form and Setting the Default Angular 2

I am working on a simple Angular 2 application and I am having problems reloading ngForm, but keeping the default value:

The expected behavior when clicking "Reset", the input field will reset the default value ("Default" in this case), as well as all Angular classes returning to default (<i.e. ng-untouched, ng-untouched, etc.) d.)

I see that the default value is also cleared even when I explicitly set it after the reset form

The following is a snippet of code:

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 (import and @Component excluded):

 export class TrainSearchTestComponent implements OnInit { id: string = 'DEFUALT'; constructor() { } ngOnInit() { } onTrainSearchClick(){ } reset(form: NgForm){ form.resetForm(); this.id = 'DEFUALT'; } } 
+5
source share
1 answer

Use form.reset :

 form.reset({ id: this.id }); 

Original answer (valid for angular @ 2)

You can pass a resetForm value that will be used as the default value for the form:

 form.resetForm({ id: this.id }); 

(of course, if your form is FormGroup and has a control named id , which should have a default value)

+9
source

Source: https://habr.com/ru/post/1263988/


All Articles