简体   繁体   中英

When using template driven forms in Angular 2, how to access the form in the component?

I have a simple template driven form like so:

HTML:

<div class="container">
    <h1>Hero Form</h1>

    <form (ngSubmit)="onSubmit()" #heroForm="ngForm">
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="name" [(ngModel)]="model.name" name="name" #name="ngModel">
      </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" [(ngModel)]="model.power" name="power">
          <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
        </select>
      </div>

      <button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
    </form>
</div>

Component:

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';

@Component({
    selector: 'at-hero',
    templateUrl: './hero.component.html',
    styleUrls: ['./hero.component.scss']
})

export class HeroComponent implements OnInit {
    constructor() {
        //
    }

    ngOnInit() {
        //
    }

    powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];

    model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');

    submitted = false;

    onSubmit() { this.submitted = true; }

    newHero() {
      this.model = new Hero(42, '', '');
    }
}

How can I:

  1. Reset the whole form from the component (not from the markup)?
  2. Reset a single form field (eg the name field) also from the component and not the markup?

You can get the form by using ViewChild

Markup

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
...
</form>

Component

ViewChild('heroForm') public heroForm: NgForm;

I suggest you also to look at Reactive Forms too. I think this will be more handy if you want to work with form in the typescript, not in the markup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM