当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular 4.x 动态创建表单实例

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

2018年04月30日  | 移动技术网IT编程  | 我要评论
本文将介绍如何动态创建表单组件,我们最终实现的效果如下: 在阅读本文之前,请确保你已经掌握 angular 响应式表单和动态创建组件的相关知识,如果对相关知识还不了解

本文将介绍如何动态创建表单组件,我们最终实现的效果如下:

在阅读本文之前,请确保你已经掌握 angular 响应式表单和动态创建组件的相关知识,如果对相关知识还不了解,推荐先阅读一下 angular 4.x reactive forms angular 4.x 动态创建组件 这两篇文章。对于已掌握的读者,我们直接进入主题。

创建动态表单

创建 dynamicformmodule

在当前目录先创建 dynamic-form 目录,然后在该目录下创建 dynamic-form.module.ts 文件,文件内容如下:

dynamic-form/dynamic-form.module.ts

import { ngmodule } from '@angular/core';
import { commonmodule } from '@angular/common';
import { reactiveformsmodule } from '@angular/forms';

@ngmodule({
 imports: [
 commonmodule,
 reactiveformsmodule
 ]
})
export class dynamicformmodule {}

创建完 dynamicformmodule 模块,接着我们需要在 appmodule 中导入该模块:

import { ngmodule } from '@angular/core';
import { browsermodule } from '@angular/platform-browser';

import { dynamicformmodule } from './dynamic-form/dynamic-form.module';

import { appcomponent } from './app.component';

@ngmodule({
 imports: [browsermodule, dynamicformmodule],
 declarations: [appcomponent],
 bootstrap: [appcomponent]
})
export class appmodule { }

创建 dynamicform 容器

进入 dynamic-form 目录,在创建完 containers 目录后,继续创建 dynamic-form 目录,然后在该目录创建一个名为 dynamic-form.component.ts 的文件,文件内容如下:

import { component, input, oninit } from '@angular/core';
import { formgroup, formbuilder } from '@angular/forms';

@component({
 selector: 'dynamic-form',
 template: `
 <form [formgroup]="form">
 </form>
 `
})
export class dynamicformcomponent implements oninit {
 @input()
 config: any[] = [];

 form: formgroup;

 constructor(private fb: formbuilder) {}

 ngoninit() {
 this.form = this.creategroup();
 }

 creategroup() {
 const group = this.fb.group({});
 this.config.foreach(control => group.addcontrol(control.name, this.fb.control('')));
 return group;
 }
}

由于我们的表单是动态的,我们需要接受一个数组类型的配置对象才能知道需要动态创建的内容。因此,我们定义了一个 config 输入属性,用于接收数组类型的配置对象。

此外我们利用了 angular 响应式表单,提供的 api 动态的创建 formgroup 对象。对于配置对象中的每一项,我们要求该项至少包含两个属性,即 (type) 类型和 (name) 名称:

  1. type - 用于设置表单项的类型,如 inputselectbutton
  2. name - 用于设置表单控件的 name 属性

creategroup() 方法中,我们循环遍历输入的 config 属性,然后利用 formgroup 对象提供的 addcontrol() 方法,动态地添加新建的表单控件。

接下来我们在 dynamicformmodule 模块中声明并导出新建的 dynamicformcomponent 组件:

import { dynamicformcomponent } from './containers/dynamic-form/dynamic-form.component';

@ngmodule({
 imports: [
 commonmodule,
 reactiveformsmodule
 ],
 declarations: [
 dynamicformcomponent
 ],
 exports: [
 dynamicformcomponent
 ]
})
export class dynamicformmodule {}

现在我们已经创建了表单,让我们实际使用它。

使用动态表单

打开 app.component.ts 文件,在组件模板中引入我们创建的 dynamic-form 组件,并设置相关的配置对象,具体示例如下:

app.component.ts

import { component } from '@angular/core';

interface formitemoption {
 type: string;
 label: string;
 name: string;
 placeholder?: string;
 options?: string[]
}

@component({
 selector: 'exe-app',
 template: `
 <div>
 <dynamic-form [config]="config"></dynamic-form>
 </div>
 `
})
export class appcomponent {
 config: formitemoption[] = [
 {
 type: 'input',
 label: 'full name',
 name: 'name',
 placeholder: 'enter your name'
 },
 {
 type: 'select',
 label: 'favourite food',
 name: 'food',
 options: ['pizza', 'hot dogs', 'knakworstje', 'coffee'],
 placeholder: 'select an option'
 },
 {
 type: 'button',
 label: 'submit',
 name: 'submit'
 }
 ];
}

上面代码中,我们在 appcomponent 组件类中设置了 config 配置对象,该配置对象中设置了三种类型的表单类型。对于每个表单项的配置对象,我们定义了一个 formitemoption 数据接口,该接口中我们定义了三个必选属性:type、label 和 name 及两个可选属性:options 和 placeholder。下面让我们创建对应类型的组件。

自定义表单项组件

forminputcomponent

dynamic-form 目录,我们新建一个 components 目录,然后创建 form-inputform-select form-button 三个文件夹。创建完文件夹后,我们先来定义 form-input 组件:

form-input.component.ts

import { component, viewcontainerref } from '@angular/core';
import { formgroup } from '@angular/forms';

@component({
 selector: 'form-input',
 template: `
 <div [formgroup]="group">
 <label>{{ config.label }}</label>
 <input
 type="text"
 [attr.placeholder]="config.placeholder"
 [formcontrolname]="config.name" />
 </div>
 `
})
export class forminputcomponent {
 config: any;
 group: formgroup;
}

上面代码中,我们在 forminputcomponent 组件类中定义了 config group 两个属性,但我们并没有使用 @input 装饰器来定义它们,因为我们不会以传统的方式来使用这个组件。接下来,我们来定义 select button 组件。

formselectcomponent

import { component } from '@angular/core';
import { formgroup } from '@angular/forms';

@component({
 selector: 'form-select',
 template: `
 <div [formgroup]="group">
 <label>{{ config.label }}</label>
 <select [formcontrolname]="config.name">
 <option value="">{{ config.placeholder }}</option>
 <option *ngfor="let option of config.options">
  {{ option }}
 </option>
 </select>
 </div>
 `
})
export class formselectcomponent {
 config: object;
 group: formgroup;
}

formselectcomponent 组件与 forminputcomponent 组件的主要区别是,我们需要循环配置中定义的options属性。这用于向用户显示所有的选项,我们还使用占位符属性,作为默认的选项。

formbuttoncomponent

import { component } from '@angular/core';
import { formgroup } from '@angular/forms';

@component({
 selector: 'form-button',
 template: `
 <div [formgroup]="group">
 <button type="submit">
 {{ config.label }}
 </button>
 </div>
 `
})
export class formbuttoncomponent{
 config: object;
 group: formgroup;
}

以上代码,我们只是定义了一个简单的按钮,它使用 config.label 的值作为按钮文本。与所有组件一样,我们需要在前面创建的模块中声明这些自定义组件。打开 dynamic-form.module.ts 文件并添加相应声明:

// ...
import { formbuttoncomponent } from './components/form-button/form-button.component';
import { forminputcomponent } from './components/form-input/form-input.component';
import { formselectcomponent } from './components/form-select/form-select.component';

@ngmodule({
 // ...
 declarations: [
 dynamicformcomponent,
 formbuttoncomponent,
 forminputcomponent,
 formselectcomponent
 ],
 exports: [
 dynamicformcomponent
 ]
})
export class dynamicformmodule {}

到目前为止,我们已经创建了三个组件。若想动态的创建这三个组件,我们将定义一个指令,该指令的功能跟 router-outlet 指令类似。接下来在 components 目录内部,我们新建一个 dynamic-field 目录,然后创建 dynamic-field.directive.ts 文件。该文件的内容如下:

import { directive, input } from '@angular/core';
import { formgroup } from '@angular/forms';

@directive({
 selector: '[dynamicfield]'
})
export class dynamicfielddirective {
 @input()
 config: object;

 @input()
 group: formgroup;
}

我们将指令的 selector 属性设置为 [dynamicfield],因为我们将其应用为属性而不是元素。

这样做的好处是,我们的指令可以应用在 angular 内置的 <ng-container> 指令上。 <ng-container> 是一个逻辑容器,可用于对节点进行分组,但不作为 dom 树中的节点,它将被渲染为 html中的 comment 元素。因此配合 <ng-container> 指令,我们只会在 dom 中看到我们自定义的组件,而不会看到 <dynamic-field> 元素 (因为 dynamicfielddirective 指令的 selector 被设置为 [dynamicfield] )。

另外在指令中,我们使用 @input 装饰器定义了两个输入属性,用于动态设置 config group 对象。接下来我们开始动态渲染组件。

动态渲染组件,我们需要用到 componentfactoryresolver viewcontainerref 两个对象。componentfactoryresolver 对象用于创建对应类型的组件工厂 (componentfactory),而 viewcontainerref 对象用于表示一个视图容器,可添加一个或多个视图,通过它我们可以方便地创建和管理内嵌视图或组件视图。

让我们在 dynamicfielddirective 指令构造函数中,注入相关对象,具体代码如下:

import { componentfactoryresolver, directive, input, oninit, 
 viewcontainerref } from '@angular/core';
import { formgroup } from '@angular/forms';

@directive({
 selector: '[dynamicfield]'
})
export class dynamicfielddirective implements oninit {
 @input()
 config;

 @input()
 group: formgroup;
 
 constructor(
 private resolver: componentfactoryresolver,
 private container: viewcontainerref
 ) {}
 
 ngoninit() {
 
 }
}

上面代码中,我们还添加了 ngoninit 生命周期钩子。由于我们允许使用 input select 类型来声明组件的类型,因此我们需要创建一个对象来将字符串映射到相关的组件类,具体如下:

// ...
import { formbuttoncomponent } from '../form-button/form-button.component';
import { forminputcomponent } from '../form-input/form-input.component';
import { formselectcomponent } from '../form-select/form-select.component';

const components = {
 button: formbuttoncomponent,
 input: forminputcomponent,
 select: formselectcomponent
};

@directive(...)
export class dynamicfielddirective implements oninit {
 // ...
}

这将允许我们通过 components['button'] 获取对应的 formbuttoncomponent 组件类,然后我们可以把它传递给 componentfactoryresolver 对象以获取对应的 componentfactory (组件工厂):

// ...
const components = {
 button: formbuttoncomponent,
 input: forminputcomponent,
 select: formselectcomponent
};

@directive(...)
export class dynamicfielddirective implements oninit {
 // ...
 ngoninit() {
 const component = components[this.config.type];
 const factory = this.resolver.resolvecomponentfactory<any>(component);
 }
 // ...
}

现在我们引用了配置中定义的给定类型的组件,并将其传递给 componentfactoryrsolver 对象提供的resolvecomponentfactory() 方法。您可能已经注意到我们在 resolvecomponentfactory 旁边使用了 <any>,这是因为我们要创建不同类型的组件。此外我们也可以定义一个接口,然后每个组件都去实现,如果这样的话 any 就可以替换成我们已定义的接口。

现在我们已经有了组件工厂,我们可以简单地告诉我们的 viewcontainerref 为我们创建这个组件:

@directive(...)
export class dynamicfielddirective implements oninit {
 // ...
 component: any;
 
 ngoninit() {
 const component = components[this.config.type];
 const factory = this.resolver.resolvecomponentfactory<any>(component);
 this.component = this.container.createcomponent(factory);
 }
 // ...
}

我们现在已经可以将 config group 传递到我们动态创建的组件中。我们可以通过 this.component.instance 访问到组件类的实例:

@directive(...)
export class dynamicfielddirective implements oninit {
 // ...
 component;
 
 ngoninit() {
 const component = components[this.config.type];
 const factory = this.resolver.resolvecomponentfactory<any>(component);
 this.component = this.container.createcomponent(factory);
 this.component.instance.config = this.config;
 this.component.instance.group = this.group;
 }
 // ...
}

接下来,让我们在 dynamicformmodule 中声明已创建的 dynamicfielddirective 指令:

// ...
import { dynamicfielddirective } from './components/dynamic-field/dynamic-field.directive';

@ngmodule({
 // ...
 declarations: [
 dynamicfielddirective,
 dynamicformcomponent,
 formbuttoncomponent,
 forminputcomponent,
 formselectcomponent
 ],
 exports: [
 dynamicformcomponent
 ]
})
export class dynamicformmodule {}

如果我们直接在浏览器中运行以上程序,控制台会抛出异常。当我们想要通过 componentfactoryresolver 对象动态创建组件的话,我们需要在 @ngmodule 配置对象的一个属性 - entrycomponents 中,声明需动态加载的组件。

@ngmodule({
 // ...
 entrycomponents: [
 formbuttoncomponent,
 forminputcomponent,
 formselectcomponent
 ]
})
export class dynamicformmodule {}

基本工作都已经完成,现在我们需要做的就是更新 dynamicformcomponent 组件,应用我们之前已经 dynamicfielddirective 实现动态组件的创建:

@component({
 selector: 'dynamic-form',
 template: `
 <form
 class="dynamic-form"
 [formgroup]="form">
 <ng-container
 *ngfor="let field of config;"
 dynamicfield
 [config]="field"
 [group]="form">
 </ng-container>
 </form>
 `
})
export class dynamicformcomponent implements oninit {
 // ...
}

正如我们前面提到的,我们使用 <ng-container>作为容器来重复我们的动态字段。当我们的组件被渲染时,这是不可见的,这意味着我们只会在 dom 中看到我们的动态创建的组件。

此外我们使用 *ngfor 结构指令,根据 config (数组配置项) 动态创建组件,并设置 dynamicfield 指令的两个输入属性:config 和 group。最后我们需要做的是实现表单提交功能。

表单提交

我们需要做的是为我们的 <form> 组件添加一个 (ngsubmit) 事件的处理程序,并在我们的动态表单组件中新增一个 @output 输出属性,以便我们可以通知使用它的组件。

import { component, input, output, oninit, eventemitter} from '@angular/core';
import { formgroup, formbuilder } from '@angular/forms';

@component({
 selector: 'dynamic-form',
 template: `
 <form 
 [formgroup]="form"
 (ngsubmit)="submitted.emit(form.value)">
 <ng-container
 *ngfor="let field of config;"
 dynamicfield
 [config]="field"
 [group]="form">
 </ng-container>
 </form>
 `
})
export class dynamicformcomponent implements oninit {
 @input() config: any[] = [];

 @output() submitted: eventemitter<any> = new eventemitter<any>();
 // ...
}

最后我们同步更新一下 app.component.ts 文件:

import { component } from '@angular/core';

@component({
 selector: 'exe-app',
 template: `
 <div class="app">
 <dynamic-form 
 [config]="config"
 (submitted)="formsubmitted($event)">
 </dynamic-form>
 </div>
 `
})
export class appcomponent {
 // ...
 formsubmitted(value: any) {
 console.log(value);
 }
}

toddmotto 大神线上完整代码请访问。

我有话说

在自定义表单控件组件中 [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;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网