首页 > 语言 > JavaScript > 正文

angular学习之动态创建表单的方法

2024-05-06 15:27:26
字体:
来源:转载
供稿:网友

准备工作

使用ng new async-form创建一个新工程,在app.module.ts中引入ReactiveFormsModule模块并在根模块中导入

import { ReactiveFormsModule } from '@angular/forms';@NgModule({ imports: [  ReactiveFormsModule ]})

构建表单元素的基类

export class QuestionBase<T> {  value: T;//表单元素的值  key: string;//表单元素键的名称  label: string;//输入元素的标题  required: boolean;//是否必输  order: number;//排序  controlType: string;//表单的类型 选择框/文本输入框  constructor(options: {    value?: T,    key?: string,    label?: string,    required?: boolean,    order?: number,    controlType?: string  } = {}) {    this.value = options.value;    this.key = options.key || '';    this.label = options.label || '';    this.required = !!options.required;    this.order = options.order === undefined ? 1 : options.order;    this.controlType = options.controlType || '';  }}

继承表单元素的基类

选择框元素的数据类型继承基类,设置了controlType 为'dropdown'并新增了属性options数组

import { QuestionBase } from './question-base';export class QuestionDropdown extends QuestionBase<string>{  controlType = "dropdown";  options: { key: string, value: string }[] = [];  constructor(options: {} = {}) {    super(options);    this.options = options["options"] || [];  }}

文本输入框元素的数据类型继承了基类,设置了controlType 为'textbox',新增了type属性,定义input的类型

import { QuestionBase } from './question-base';export class QuestionTextbox extends QuestionBase<string> {  controlType = "textbox";  type:string;  constructor(options:{} ={}){    super(options);    this.type = options["type"]||""  }}

生成数据

根据表单元素的派生类生成表单的数据。可以引入一个服务类,提供表单数据。

 getQuestions(){  let questions:QuestionBase<any>[]=[   new QuestionDropdown({    key:'brave',    label:'Bravery Rating',    options:[     {key:'solid',value:'Solid'},     {key:'great',value:'Great'},     {key:'good',value:'Good'},     {key:'unproven',value:'Unproven'}    ],    order:3   }),   new QuestionTextbox({    key:'firstName',    label:'First name',    value:"Bombasto",    required:true,    order:1   }),   new QuestionTextbox({    key:'emailAddress',    label:"Email",    type:'email',    order:2   })  ];  return questions.sort((a, b) => a.order - b.order); }

将数据转成FormControl类型

可以专门提供一个服务类,将表单的数据转成FormControl类型

 toFormGroup(questions: QuestionBase<any>[]) {  let group: any = {};  questions.forEach(question => {   group[question.key] = question.required?new FormControl(question.value||"",Validators.required)   :new FormControl(question.value||"");  });  return new FormGroup(group); }            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选