1
votes

I'm learning Angular, and I cannot figure out how to reset the validation of a template driven form.

In the official tutorial, they show a method to reset the form so it doesn't show any error messages even if the untouched field is empty, but it doesn't work for me.

Here is the official example of the app, where "New Hero (with reset)" and "New Hero (without reset)" seem to result in the same situation (red error indicators on the left of the input, "Name is required" warning under the name input). I remove the value in the input and press the button, but the error message remains:

https://stackblitz.com/angular/kmoqyljrgve

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
  <div class="form-group">
    <label for="name">Name</label>
    <input type="text" class="form-control" id="name"
           required
           [(ngModel)]="model.name" name="name"
           #name="ngModel">
    <div [hidden]="name.valid || name.pristine"
         class="alert alert-danger">
      Name is required
    </div>
  </div>

  <div class="form-group">
    <label for="alterEgo">Alter Ego</label>
    <input type="text" class="form-control" id="alterEgo"
           [(ngModel)]="model.alterEgo" name="alterEgo">
  </div>

  <div class="form-group">
    <label for="power">Hero Power</label>
    <select class="form-control" id="power"
            required
            [(ngModel)]="model.power" name="power"
            #power="ngModel">
      <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
    </select>
    <div [hidden]="power.valid || power.pristine" class="alert alert-danger">
      Power is required
    </div>
  </div>

  <button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
  <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
  <i>with</i> reset

  &nbsp;&nbsp;
  <button type="button" class="btn btn-default" (click)="newHero()">New Hero</button>
  <i>without</i> reset

 <!-- NOT SHOWN IN DOCS -->
  <div>
    <hr>
    Name via form.controls = {{showFormControls(heroForm)}}
  </div>
 <!-- - -->
</form>

Can anyone explain this or show me what i misunderstood?

Thanks in advance

2
Post your code here instead of just showing a link - Alf Moh

2 Answers

1
votes

You can reset the form by using the form resetForm form.

form.resetForm();

Where form is the instance of your form heroForm

0
votes
For select drop down use the below:

/* html */

<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)" style="font-family: Montserrat-Regular;">
    <div class="form-group">
        <input type="text" class="form-control" id="name" name="name" aria-describedby="emailHelp" placeholder="Name" 
        #name="ngModel" [class.is-invalid]="name.invalid && name.touched" ngModel [(ngModel)]="drinkname" required>
        <p style="color: red; font-size: 12px" [class.d-none]="name.valid || name.untouched">Name is required</p>
    </div>
    <div class="form-group">
        <select class="form-control" id="rating" name="rating" #rating="ngModel" 
        [class.is-invalid]="rating.invalid && rating.touched" ngModel [(ngModel)]="drinkrating" required>
        <option value="undefined" hidden>Select Rating</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
        </select>
        <p style="color: red; font-size: 12px" [class.d-none]="count.valid || count.untouched">Count is required</p>
    </div>
    <button type="submit" class="btn btn-primary" [disabled]="itemForm.form.invalid">Submit</button>
  </form>


/* ts */

onSubmit(userForm: NgForm) {

      this.formData = new FormData();
      this.formData.append('name', this.drinkname);
      this.formData.append('rating', this.drinkrating);

    const options = {
      headers: new HttpHeaders()
        .set('Authorization', 'Bearer ' + localStorage.getItem('token'))
    }

    this.http.post('http://localhost:8099/createi', this.formData, options)
      .subscribe(
        data => {
          var status = data['status'];
          var message = data['message'];
          if (status == -1){
            this.notifyService.showError(message,"Exists");
            return;
          }

          // this is the important code, dont worry about name input because it will use placeholder as default value
          userForm.resetForm({
            rating: "undefined",

         });
        },
        error => console.log(error)
      );
  }