在Angular 2中使用模板驱动表单时,如何访问组件中的表单?

时间:2017-12-13 17:03:12

标签: javascript angular

我有一个简单的模板驱动形式,如下所示:

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>

组件:

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, '', '');
    }
}

我怎么能:

  1. 从组件重置整个表单(而不是从标记中重置)?
  2. 还要从组件重置单个表单字段(例如名称字段)而不是标记?

1 个答案:

答案 0 :(得分:3)

您可以使用array( key => value, key2 => value2, key3 => value3, ... )

获取form

加价

ViewChild

<强>组件

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

我建议您也查看Reactive Forms。如果您想在打字稿中使用ViewChild('heroForm') public heroForm: NgForm; 而不是在标记中使用

,我认为这会更方便