如有需要動態驗證、動態產生表單和比較複雜類型的表單狀況,使用 Reactive Form 處理應當會比 Template-Drive Form 好解決.
app.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
@NgModule({
// ...
imports: [
BrowserModule,
ReactiveFormsModule,
HttpModule
],
// ...
})
export class AppModule { }
引用完 Reactive Form 接下來先修改 template
app.component.html
<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
<input formControlName="name" placeholder="Your name">
<input formControlName="email" placeholder="Your email">
<input formControlName="message" placeholder="Your message">
<button type="submit">Send</button>
</form>
其中 template 用到了以下的 directive
app.component.html
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
// ...
})
export class AppComponent implements OnInit {
myForm: FormGroup;
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl('Benedict'),
email: new FormControl(''),
message: new FormControl('')
});
}
onSubmit(form: FormGroup) {
console.log('Valid?', form.valid); // true or false
console.log('Name', form.value.name);
console.log('Email', form.value.email);
console.log('Message', form.value.message);
}
}
參考