Angular响应式表单相比较模板驱动表单更大操做性、更易测试性。所以,我更推荐这类表单创造方式。typescript
当一个用于修改用户信息的表单,数据的来源老是来自远程;而对于一个 FormGroup
的建立总在 ngOnInit
中完成。所以,这里会有一个表单更新值的问题。app
而一般咱们会透过 FormGroup
下的三种方式 setValue
、patchValue
、reset
将值写入表单当中。测试
固然,或许我说的这三种方式时你压根就没有作过,那说明在表单上你依赖的是双向绑定 [(ngModel)]
,这自己就不是符合 Angular 响应式表单的牛B之处了。所以,在此咱们不讨论这种这种方式。ui
咱们模拟一个用户信息修改的表单所须要的字段,可能包括:email
、nickname
等。this
若是以API的方式与现实字段之间产生一个关联,那么 FormGroup
表示一个表单,FormControl
表示表单中的字段。所以,FormControl
必须包裹在 FromGroup
下面。双向绑定
下面,咱们先简单的构建一个响应式表单。code
别忘记导入
ReactiveFormsModule
模块。orm
@Component({ selector: 'app-validation', template: ` <form [formGroup]="form" (ngSubmit)="_submitForm(form)"> <input type="email" formControlName="email"> <input type="text" formControlName="nickname"> <button type="submit" [disabled]="form.invalid">Submit</button> </form> ` }) export class UserEditComponent { constructor(private fb: FormBuilder, private route: ActivatedRoute) {} ngOnInit() { this.form = this.fb.group({ email: ['', Validators.compose([Validators.required, Validators.email])], nickname: ['', [Validators.required]] }); this.route.params .switchMap((params: Params) => loadUser(+params['id'])) .subscribe(data => { // Updating value }); } loadUser() { return Observable.of({ email: 'xx@xx.com', nickname: 'cipchk' }).delay(1000); } _submitForm({ value }) { // Save value } }
以上的这些代码再熟悉不过了。假设 UserEditComponent
是由路由 /user/edit/1
触发,那么会发生几个几件事情。对象
首先,建立一个空的响应式表单 form
。ip
this.form = this.fb.group({ email: ['', Validators.compose([Validators.required, Validators.email])], nickname: ['', [Validators.required]] });
表单的内容有 email
、nickname
两个字段。
email
必填项且必须是标准 Email 格式。nickname
必填项。然而,HTML中,除了 formGroup
、formControlName
的配置之外,也看不到任何有关对表单的校验代码。但,当咱们输入一个无效 Email 时 input
会自动加上 ng-invalid
类。
这即是响应式表单的魅力。
如今咱们回到正题,将分别针对 setValue
、patchValue
、reset
三种不一样更新表单值实际上会发生什么。
patchValue
正如名称那般,打补丁。假如咱们在 email
文本框里输入:xx@xx.com,接着调用:
this.form.patchValue({ nickname: 'cipchk' });
最终的结果是两个字段同时拥有值,由于这里咱们只对 nickname
设置了值,而 email
并无,那只是先前人为录入的数据。
那么 patchValue
实际上作了什么呢?
patchValue(value: {[key: string]: any}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { Object.keys(value).forEach(name => { if (this.controls[name]) { this.controls[name].patchValue(value[name], {onlySelf: true, emitEvent: options.emitEvent}); } }); this.updateValueAndValidity(options); }
首先,利用 Object.keys
查找主键,并以主键名查找相应的 FromControl
实例对象:
Object.keys({ nickname: 'cipchk' }).forEach(name => { console.log(name); }); // [ 'nickname' ]
而后,更新值:
this.controls[name].patchValue(value[name], {onlySelf: true, emitEvent: options.emitEvent});
而 FromControl
实例的 patchValue
和 FromGroup
不一样,他只是单纯的更新 FromControle
实例对象中的 value
值。
value
至关于表单实际值,还记得先前HTML中的 formControlName
就是将实例与DOM产生联系,这也就是为何不须要在DOM中使用双向绑定的缘由。
setValue
跟 patchValue
有一点不同,当咱们提供一个 FromGroup
中并不存在的字段时,会抛出一个错误。除此以外,与 patchValue
并没有不一样。
setValue(value: {[key: string]: any}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._checkAllValuesPresent(value); Object.keys(value).forEach(name => { this._throwIfControlMissing(name); this.controls[name].setValue(value[name], {onlySelf: true, emitEvent: options.emitEvent}); }); this.updateValueAndValidity(options); }
主要是 this._throwIfControlMissing(name);
当传递的对象有一个不是 FromControl
时直接抛弃一个 Error
。
_throwIfControlMissing(name: string): void { if (!Object.keys(this.controls).length) { throw new Error(` There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout). `); } if (!this.controls[name]) { throw new Error(`Cannot find form control with name: ${name}.`); } }
reset
正常状况下,表单须要提供一个重置按钮时调用此方法。
reset(formState: any = null, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void { this._applyFormState(formState); this.markAsPristine(options); this.markAsUntouched(options); this.setValue(this._value, options); }
除了恢复校验状态之外。最后一句代码是调用 setValue
,这等同上一节说的。所以,当咱们调用此方法时,容许咱们直接传递一个数据对象作为重置后的默认值,好比:
<button (click)="form.reset({ nickname: 'xx' })">Reset</button>
重置表单后并设置 nickname
默认值为:xx。
每一种不一样更新值方式都会有不同的结果,当咱们回头过看开头中留下来的:
// Updating value
若是是你,你会怎么写呢?
Happy coding!