简体   繁体   English

如何使用打字稿类生成对象的表单元素以及如何使用角形的反应性表单生成对象

[英]How to generate form elements using typescript classes and objects using Reactive Forms in angular

I have a class file as follows. 我有一个类文件,如下所示。

export class ClassA {
    description: string;
    type: string;
    order: number;
    constructor(descrption: string, type: string, order: number) {
        this.description = descrption;
        this.type = type;
        this.order = order;
    }
}

Now I want to create form elements(text boxes) using this class through type script. 现在,我想通过类型脚本使用此类创建表单元素(文本框)。 In my html page the code is as follows 在我的html页面中,代码如下

<form [formGroup]="myForm">

</form>

In my typescript file ie (.ts )file the code is as follows. 在我的打字稿文件(即(.ts)文件)中,代码如下。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  arr = Array<ClassA>();
  r1: ClassA;
  r2: ClassA;
  myForm:FormGroup;
  constructor() {
    this.r1 = new ClassA('description1', 'text', 1);
    this.arr.push(this.r1);
    this.r2 = new ClassA('description2', 'text', 2);
    this.arr.push(this.r2);
  }
  ngOnInit() {
    console.log(this.arr);
  }
}

Now using this formGroup how to make these class fields as input elements in form dynamically ? 现在使用此formGroup如何动态地将这些类字段作为表单中的输入元素?

What I would do, since you have a class and know how the build of the form should look like, I'd use it to push formgroups to a FormArray , so first build form, iterate your array and push each object to array as formGroup: 我要做什么,因为您有一个类,并且知道表单的构建应如何,因此我将使用它将表单组推入FormArray ,因此首先构建表单,迭代数组并将每个对象作为formGroup推入数组:

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    formArray: this.fb.array([])
  });
  this.r1 = new ClassA('description1', 'text', 1);
  this.arr.push(this.r1);
  this.r2 = new ClassA('description2', 'text', 2);
  this.arr.push(this.r2);

  this.arr.forEach(x => {
    let formArr = this.myForm.controls.formArray as FormArray;
    this.arr.forEach(x => {
      formArr.push(this.fb.group({
        description: [x.description],
        type: [x.type],
        order: [x.order]
      }))
    })
  })
}

and if you want to push new object of class ClassA , you can do it like: 如果要推送类ClassA新对象,可以执行以下操作:

formArr.push(this.fb.group(new ClassA('desc3','type3',3)))

Then in template just iterate this form array: 然后在模板中迭代此表单数组:

<form [formGroup]="myForm">
  <div formArrayName="formArr">
    <div *ngFor="let item of myForm.get('formArr').controls; let i = index" [formGroupName]="i">
      <input formControlName="description" />
      <input formControlName="type" />
      <input formControlName="order" />
    </div>
  </div>
</form>

Hopefully this is something you are looking for! 希望这是您正在寻找的东西! :) :)

StackBlitz StackBlitz

Just create a component and take a object as input. 只需创建一个组件并将一个对象作为输入即可。 You can get all properties of a object by following code: 您可以通过以下代码获取对象的所有属性:

Object.keys(obj);

Above code will give you all keys of your object. 上面的代码将为您提供对象的所有键。 Now create a formGroup and add FormControls. 现在创建一个formGroup并添加FormControls。 In Template use ngfor to render inputs. 在模板中,使用ngfor渲染输入。

Use following code: 使用以下代码:

import { Component, Input } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from "@angular/forms";

@Component({
  selector: 'app-form',
  template: `
    <form [formGroup]="myForm">
      <div *ngFor="let formKey of objKeys">
        <input type="text" formControlName="{{formKey}}" />
      </div>

      {{myForm.value | json}}
    </form>
  `,
})
export class FormComponent  {
  public myForm: FormGroup;
  public myObj = {
    firstName: "",
    lastName: ""
  };
  public objKeys: string[] = [];
  constructor(private fb: FormBuilder) {
    this.objKeys = Object.keys(this.myObj);
    console.log(this.objKeys);
    this.myForm = fb.group({});
    Object.keys(this.myObj).forEach(key => {
    this.myForm.addControl(key, new FormControl(this.myObj[key]));      
    })
  }
}

Hope it will help 希望对你有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM