Angular 4.x 动态创建表单实例(4)

import { Component } from '@angular/core'; @Component({ selector: 'exe-app', template: ` <div> <dynamic-form [config]="config" (submitted)="formSubmitted($event)"> </dynamic-form> </div> ` }) export class AppComponent { // ... formSubmitted(value: any) { console.log(value); } }

Toddmotto 大神线上完整代码请访问- toddmott/angular-dynamic-forms

我有话说

在自定义表单控件组件中 [formGroup]="group" 是必须的么?

form-input.component.ts

<div [formGroup]="group"> <label>{{ config.label }}</label> <input type="text" [attr.placeholder]="config.placeholder" [formControlName]="config.name" /> </div>

如果去掉 <div> 元素上的 [formGroup]="group" 属性,重新编译后浏览器控制台将会抛出以下异常:

Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). Example: <div [formGroup]="myGroup"> <input formControlName="firstName"> </div> In your class: this.myGroup = new FormGroup({ firstName: new FormControl() });

在 formControlName 指令中,初始化控件的时候,会验证父级指令的类型:

private _checkParentType(): void { if (!(this._parent instanceof FormGroupName) && this._parent instanceof AbstractFormGroupDirective) { ReactiveErrors.ngModelGroupException(); } else if ( !(this._parent instanceof FormGroupName) && !(this._parent instanceof FormGroupDirective) && !(this._parent instanceof FormArrayName)) { ReactiveErrors.controlParentException(); } }

那为什么要验证,是因为要把新增的控件添加到对应 formDirective 对象中:

private _setUpControl() { this._checkParentType(); this._control = this.formDirective.addControl(this); if (this.control.disabled && this.valueAccessor !.setDisabledState) { this.valueAccessor !.setDisabledState !(true); } this._added = true; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wypgxx.html