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

 

转载于:https://www.cnblogs.com/sgciviolence/p/6495387.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值