欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-23 22:24:33
准备工作 使用ng new async-form创建一个新工程,在app.module.ts中引入reactiveformsmodule模块并在根模块中导入...

准备工作

使用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);
 }

到这里就已经完整构建出一组formcontrol 实例了。

为数据提供页面模板

<div [formgroup]="form">
 <label [attr.for]="question.key">{{question.label}}</label>
 <div [ngswitch]="question.controltype">
  <input *ngswitchcase="'textbox'" [formcontrolname]= "question.key" 
  [id]="question.key" [type]="question.type">
  <select [id]="question.key" *ngswitchcase="'dropdown'"
   [formcontrolname]="question.key">
   <option *ngfor="let opt of question.options" [value]="opt.key">
    {{opt.value}}
   </option>
  </select>
 </div>
 <div class="errormessage" *ngif="!isvalid">
  {{question.label}} is required
 </div>
</div>

通过formgroup指令绑定表单数据,ngswitch指令来选择生成的模板,formcontrolname指令绑定对应的表单数据的key值

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

import {questionbase} from '../question-base';

@component({
 selector: 'app-dynamic-form-question',
 templateurl: './dynamic-form-question.component.html',
 styleurls: ['./dynamic-form-question.component.less']
})
export class dynamicformquestioncomponent implements oninit {
 @input() question:questionbase<any>;
 @input() form :formgroup;
 get isvalid(){
  return this.form.controls[this.question.key].valid;
 }
 constructor() { }

 ngoninit() {
 }

}

表单组件需要两个输入,form和question,form来获取对应表单的键值是否校验成功,question来渲染对应表单输入元素。使用app-dynamic-form-question标签来使用组件

引用表单组件

  <div *ngfor="let question of questions" class="form-row">
   <app-dynamic-form-question [question]="question" [form]="form"></app-dynamic-form-question>
  </div>

获取到questions数据后,通过*ngfor指令来渲染单个表单组件。

结束

到这里就完成了动态创建表单的功能,以这种方式来创建表单,我们只需要开始时构建出指定的单个输入框或者其他表单元素的样式之后,通过改变数据来控制表单的内容,便于后期维护。

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