首页 文章

如何使用 angularcript 类和对象在角度中使用 Reactive Forms 生成表单元素

提问于
浏览
0

我有一个类文件如下。

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;
    }
}

现在我想通过类型脚本使用这个类来创建表单 elements(text box。在我的 html 页面中,代码如下

<form [formGroup]="myForm">

</form>

在我的打字稿文件 i.e(.ts )file,代码如下。

@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);
  }
}

现在使用这个 formGroup 如何动态地将这些类字段作为输入元素?

2 回答

  • 0

    只需创建一个组件并将对象作为输入。您可以通过以下代码获取对象的所有属性:

    Object.keys(obj);
    

    上面的代码将为您提供对象的所有键。现在创建一个 formGroup 并添加 FormControls。在模板中使用 ngfor 来渲染输入。

    使用以下代码:

    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]));      
        })
      }
    }
    

    希望它会有所帮助

  • 0

    我会做什么,因为你有一个类,并知道表单的构建应该是什么样的,我会用它来将表单组推送到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]
          }))
        })
      })
    }
    

    如果你想推送类ClassA的新对象,你可以这样做:

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

    然后在模板中迭代这个表单数组:

    <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>
    

    希望这是你正在寻找的东西! :)

    **** StackBlitz

相关问题