表單驗證 須要引入FormsModule, ReactiveFormsModule模塊bootstrap
// app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule, ReactiveFormsModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
在須要作驗證的組件裏插入app
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
模板裏post
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value, myForm.valid)"> <div> <label>Name</label> <input type="text" formControlName="name"> <small [hidden]="myForm.controls.name.valid || (myForm.controls.name.pristine && !submitted)"> Name is required (minimum 5 characters). </small> </div> <div formGroupName="address"> <label>Address</label> <input type="text" formControlName="street"> <small [hidden]="myForm.controls.address.controls.street.valid || (myForm.controls.address.controls.street.pristine && !submitted)"> street required </small> </div> <div formGroupName="address"> <label>Postcode</label> <input type="text" formControlName="postcode"> </div> <button type="submit">Submit</button> </form>
在ngOninit事件裏建立FormGroup,有兩種方式能夠建立ui
建立FormGroup方法1this
ngOnInit() { // the long way this.myForm = new FormGroup({ name: new FormControl('', [<any>Validators.required, <any>Validators.minLength(5)]), address: new FormGroup({ street: new FormControl('', <any>Validators.required), postcode: new FormControl('8000') }) }); }
建立FormGroup方法2spa
constructor(fb: FormBuilder) { // the short way this.myForm = this._fb.group({ name: ['', [<any>Validators.required, <any>Validators.minLength(5)]], address: this._fb.group({ street: ['', <any>Validators.required], postcode: [''] }) }); }
設置值,例如修改數據時code
const people = { name: 'Jane', address: { street: 'High street', postcode: '94043' } }; (<FormGroup>this.myForm).setValue(people, { onlySelf: true });