Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting form and set default value Angular 2 [duplicate]

Tags:

forms

angular

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';
  }
}
like image 423
Tony Scialo Avatar asked Feb 08 '17 19:02

Tony Scialo


1 Answers

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)

like image 64
smnbbrv Avatar answered Oct 28 '22 13:10

smnbbrv