Angular use dynamic forms

The purpose is to use dynamic forms do not have to manually write much HTML code, just by the number and the type of data to dynamically generate forms After setting up and improve efficiency. Introducing dynamic form in Angular the official website, interspersed with some of the business side of things, increasing the difficulty of people to learn unfamiliar, here is to demonstrate how to generate direct and use of dynamic forms.
When using dynamic forms, it may be necessary input type, textarea or other type of form type, etc., to get the data in the build-related controls, the need to develop some basic things, such as the control type, value and so on.

First, create a base classThis look at their own needs, not to the base class is their own choice, directly take some configuration official website here

//基类
export class BaseControl<T>{
    value: T;
    key: string;
    label: string;
    required: boolean;
    order: number;
    controlType: string;
    placeholder: string;

    constructor(options: {
        value?: T,
        key?: string,
        label?: string,
        required?: boolean,
        order?: number,
        controlType?: string,
        placeholder?: 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 || '';
        this.placeholder = options.placeholder || '';
    }
}

Create sub-control class

//textarea类
export class TextArea extends BaseControl<string>{
    controlType = "textarea";
    rows: number;
    constructor(options: {} = {}) {
        super(options);
        this.rows = options['rows'] || 1;
    }
}
//input类,默认文本类型
export class TextBox extends BaseControl<string>{
    controlType = "textbox";
    type: string;
    constructor(options: {} = {}) {
        super(options);
        this.type = options["type"] || "";
    }
}

Then build controls

export class DynamicFromComponent implements OnInit {

  constructor() { }

  form:FormGroup;
  controls:BaseControl<any>[];
  ngOnInit() {
    this.controls=this.createControls();
    this.form=this.toFromGroup(this.controls);
  }
  //构建控件,如果需要放一些默认数据以及其他的验证都在这里进行
  createControls() {
    return [
      new TextArea({
        placeholder: "地方描述,最多120字。",
        rows: 3,
        key:"desc1"
      }),
      new TextArea({
        placeholder: "路线描述,最多120字。",
        rows: 3,
        key:"desc2"
      }),
      new TextBox({
        placeholder: "用户名",
        value:"张三",
        key:"userName"
      })
    ]
  }
  //循环控件加到formgroup上
  toFromGroup(controls:BaseControl<any>[]){
    let group: any = {};
    controls.forEach(item => {
      //这个是要绑到formControlName上的值,如果都不设置具体名称的话,
      //最后提交拿到只有最后改变的那个控件的值,我这写的和官网上的不一样
      //我这里是一种投机行为
      group[item.key] = new FormControl(item.key || "");
    });
    return new FormGroup(group);
  }

  onSubmit(){
  	//这里是提交时获取到的所有表单数据,如果都不填获取的是默认的值
    console.log(this.form.value);
  }

}

Reception Use

<form (ngSubmit)="onSubmit()" [formGroup]="form">
  <div *ngFor="let item of controls">
    <div [ngSwitch]="item.controlType">
      <!--通过判断类型来显示哪种表单-->
      <input *ngSwitchCase="'textbox'" [type]="item.type" value="{{item.value}}" [formControlName]="item.key"
        placeholder="{{item.placeholder}}">
      <textarea *ngSwitchCase="'textarea'" value="{{item.value}}" rows="{{item.rows}}" [formControlName]="item.key"
        placeholder="{{item.placeholder}}"></textarea>
    </div>
  </div>
  <button type="submit">保存</button>
</form>

result
Here Insert Picture Description

Published 28 original articles · won praise 1 · views 8727

Guess you like

Origin blog.csdn.net/moqiuqin/article/details/98874932