[英]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: 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: 我怎样才能:
You can get the form
by using ViewChild
您可以使用
ViewChild
来获取form
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 我想如果您想在打字稿中而不是在标记中使用
form
,这会更方便
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.