CJP
CJP

Reputation: 99

Reset forms on angular 2

im trying to get some values in forms using the submit event. But i can´t reset those forms later. Im trying to use an id called "myForm" and an onclick function

                        <form (Submit)="addMarker()" id="myForm">
                            <div class="row">
                            <div class="col">
                            <input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
                            </div>
                            <div class="col">
                            <input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
                            </div>
                            <div class="col-3">
                            <button type="submit" class="btn btn-primary" onclick="myFunction()">Agregar Marcador</button>
                            </div>
                            </div>
                        </form>

Script:

function myFunction() {
    document.getElementById("myForm").reset();
}

Upvotes: 0

Views: 419

Answers (2)

Akash Agrawal
Akash Agrawal

Reputation: 2299

In your HTML:

<form (submit)="addMarker(myForm)" id="myForm" #myForm="ngForm"> // <-- Notice the "#"
    <div class="row">
        <div class="col">
            <input type="text" [(ngModel)]="lat" name="lat" class="form-control" placeholder="Latitud">
        </div>
        <div class="col">
            <input type="text" [(ngModel)]="lng" name="lng" class="form-control" placeholder="Longitud">
        </div>
        <div class="col-3">
            <button type="submit" class="btn btn-primary">Agregar Marcador</button>
        </div>
    </div>
</form>

In your ts:

Import NgForm first by adding:

import { NgForm } from '@angular/forms';

Function to reset the form:

addMarker(form: NgForm) {
    //do something and then reset the form
    form.resetForm();
}

Upvotes: 3

Ankur
Ankur

Reputation: 3199

For Angular 2 Final, we now have a new API that cleanly resets the form:

@Component({...})
class App {

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

This API not only resets the form values, but also sets the form field states back to ng-pristine and ng-untouched.

Upvotes: 0

Related Questions