1. 什么是响应式表单?
响应式表单提供了一种模型驱动的方式来处理表单输入,其中的值会随时间而变化。
响应式表单使用显示的,不可变的方式,管理表单在特定时间点上的状态。对表单状态的每一次变更都会返回一个新的状态,这样可以在变化时维护模型的整体性。
—— Angular文档
2. 响应式表单的使用
2.1 单个表单控件
FormControl的实例可以跟踪独立表单控件的值和验证状态。
2.1.1 使用步骤(示例)
步骤1: 在module.ts中导入ReactiveFormsModule模块1。
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
ReactiveFormsModule
],
})
export class AppModule { }
步骤2: 在组件类导入FormControl类2,并创建一个FormControl实例。
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms'; // 导入FormControl
@Component({
selector: 'app-welcome',
templateUrl: './welcome.component.html',
styleUrls: ['./welcome.component.css']
})
export class WelcomeComponent implements OnInit {
// 创建FormControl实例
name = new FormControl('');
constructor() { }
ngOnInit() {
}
}
步骤3: 在模板中注入该控件
<label>
FormControl测试:<input nz-input [formControl]="name" placeholder="输入测试信息">
</label>
<label>
输入的测试信息为:{{name.value}}
</label>
若想设置表单控件的值,可以使用FormControl提供的 setValue() 方法。
2.2 表单控件分组
FormGroup实例可以跟踪一组 FormControl 实例的值和有效性状态。
当创建FormGroup时,其中的每一个控件都会根据其名字进行跟踪。
2.2.1 使用步骤(示例)
步骤1:创建FormGroup实例
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms'; // 导入FormControl和FormGroup类
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
// 创建FromGroup实例
profileForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
}
FormGroup 实例拥有和 FormControl 实例相同的属性(比如 value、untouched)和方法(比如 setValue())。
步骤2:关联FormGroup的模型与视图
这个表单组跟踪其中每个控件的状态和值变化,所以如果其中的某个控件的状态或值变化了,父控件会发出一次新的状态变更或值变更事件。
该控件组的模型来自于它的所有成员。在定义了这个模型之后,必须更新模板,来把该模型反映到视图中。
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
解释:
模型中创建的FormGroup实例通过FromGroup指令绑定到form元素上,在该模型和表单中的输入框之间创建一个通讯层。
由FormControlName指令提供的formControlName属性把每个输入框和FormGroup中定义的表单控件绑定起来。这些表单控件会和相应的元素通讯,它们还把更改传递给FormGroup,这个FormGroup是模型值的权威数据源。
2.2.2 保存表单数据
组件从用户那里获得输入,但在真实的场景中,你可能想要先捕获表单的值,等将来在组件外部进行处理。
FormGroup 指令会监听 form 元素发出的 submit 事件,并发出一个 ngSubmit 事件,用来绑定一个回调函数。
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
组件类中的onSubmit()方法会捕获FromGroup示例(这里即profileForm)的当前值。
要保持该表单的封装性,就要使用EventEmitter向组件外部提供该表单的值。
获取表单的值用:this.profileForm.value
form 标签所发出的 submit 事件是原生 DOM 事件,通过点击类型为 submit 的按钮可以触发本事件。
<button type="submit">Submit</button>
2.3 使用FormBuilder来生成表单控件
2.3.1 使用步骤(示例)
步骤1: 导入FormBuilder类
import { FormBuilder } from '@angular/forms';
步骤2: 注入FormBuilder服务
constructor(private fb: FormBuilder) { }
步骤3: 生成表单控件
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
profileForm = this.fb.group({
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
});
constructor(private fb: FormBuilder) { }
}
注意:这里使用group()方法来定义属性,每个控件名对应的值都是一个数组,这个数组中的第一项是其初始值,第二项和第三项提供同步和异步验证器。
在上面的描述中,已经为表单创建了表单控件,下面结合验证器来进行表单验证。
2.4 表单验证
响应式表单包含了一组开箱即用的常用验证器函数。这些函数接收一个控件,用以验证并根据验证结果返回一个错误对象或空值。
步骤1: 创建表单控件
步骤2: 导入 验证器函数
import { Validators } from '@angular/forms';
步骤3: 添加验证器静态方法
将验证器静态方法设置为表单控件值数组的第二项。
验证器静态方法如下:
Validators.min(n):该验证器要求控件值最小值为n(n为数字)。Validators.max(n):该验证器要求控件值最大值为n(n为数字)。Validators.required:该验证器要求控件具有非空值,即该控件所表示的字段必填。Validators.minLength(n):该验证器要求控件值的最小长度为n(n为数字)。Validators.maxLength(n):该验证器要求控件值的最大长度为n(n为数字)。- ……
详细的验证器静态方法请查阅 官方文档-Validators。

本文深入解析Angular响应式表单的使用,涵盖FormControl、FormGroup、FormBuilder的配置与操作,以及如何实施表单验证。
4575





