FormControl: 表单中的每一个item
userName: FormControl = new FormControl('aaa')
FormGroup: 表单数据分组,可以嵌套
formModel: FormGroup = new FormGroup({
from: new FormControl(),
to: new FormControl()
})
FormArray: 表单同样数据的集合
emails: FormArray = new FormArray([
new FormControl('a@a.com'),
new FormControl('b@b.com')
])
1.引入响应式表单依赖
imports: [
ReactiveFormsModule
],
2.编写布局文件
<form [formGroup]="formModel" (submit)="onSubmit()">
<div>
用户名: <input formControlName="userName" type="text">
</div>
<div [hidden]="!formModel.hasError('required', 'userName')">用户名是必填</div>
<div formGroupName="dateRange">
开始时间:<input formControlName="from" type="date">
结束时间:<input formControlName="to" type="date">
</div>
<div>
<ul formArrayName="emails">
<li *ngFor="let e of this.formModel.get('emails').controls; let i = index">
<input type="text" [formControlName]="i">
</li>
</ul>
<button type="button" (click)="addEmail()">增加Email</button>
</div>
<div>
<button type="submit">保存</button>
</div>
</form>
3.ts文件绑定数据
formModel: FormGroup = new FormGroup({
userName: new FormControl(),
dateRange: new FormGroup({
from: new FormControl(),
to: new FormControl()
}),
emails: new FormArray([
new FormControl('a@email.com'),
new FormControl('b@email.com')
])
});
// FormBuilder 简化,可增加参数添加校验规则
// constructor(private formBuilder: FormBuilder) { }
// formModel: FormGroup = this.formBuilder.group({
// userName: ['', [Validators.required, this.userNameValidator]], // 校验规则
// dateRange: this.formBuilder.group({
// from: [''],
// to: ['']
// }),
// emails: this.formBuilder.array([
// ['a@email.com'],
// ['b@email.com']
// ])
// });
// 自定义校验器
userNameValidator(control: FormControl): any {
let valid = control.value.length > 3;
return valid ? null : {name: '名字长度小于三'};
}
emails: new FormArray([
new FormControl('a@email.com'),
new FormControl('b@email.com')
])
});
addEmail() {
let emails = this.formModel.get('emails') as FormArray;
emails.push(new FormControl());
}
onSubmit() {
let valid = this.formModel.valid; // 判断校验结果
let error = this.formModel.get('userName').errors; // 返回错误信息
console.log(this.formModel.value);
}
状态字段
touched和untouched // 是否获取过焦点(可控制错误信息的显示和不显示)
<div [hidden]="formModel.get('userName').untouched"></div>
对应css类选择器.ng-touched``.ng-untouched
pristine和dirty // 值有没有被改变过
<div [hidden]="formModel.get('userName').pristine">
对应css类选择器.ng-pristine``.ng-dirty
pending // 异步请求中
对应css类选择器.ng-pending