angular 2+ 表单验证

表单验证 需要引入FormsModule, ReactiveFormsModule模块

// 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 { }

在需要做验证的组件里插入

import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';

模板里

<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,有两种方式可以创建

创建FormGroup方法1

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方法2

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: ['']
            })
        });
}

设置值,例如修改数据时

 const people = {
            name: 'Jane',
            address: {
                street: 'High street',
                postcode: '94043'
            }
        };

(<FormGroup>this.myForm).setValue(people, { onlySelf: true });