将多维数组转换为formGroup的简单方法

时间:2019-10-30 15:11:42

标签: angular angular-reactive-forms

我从API获取多维数组来编辑数据。现在,我想将该数组转换为角度formgroup

我已经尝试过循环,嵌套循环,用于在formGroup中转换该数组。但是我认为应该有一个简单的方法

假设我的数据如下:

const arr = [
        {
            type: 'student',
            name: {
                first: 'Nick',
                last: 'Peru'
            },
            skills: [
                {
                    title: 'programming',
                    desc: 'Whatever'
                },
                {
                    title: 'design',
                    desc: 'Whatever'
                }
            ]
        },
        ...
]

我想要这样的东西

fb.group({
        data: fb.array([
            fb.group({
                type: 'student',
                name: fb.group({
                    first: 'Nick',
                    last: 'Peru'
                }),
                skills: fb.array([
                    fb.group({
                        title: 'programming',
                        desc: 'Whatever'
                    }),
                    fb.group({
                        title: 'design',
                        desc: 'Whatever'
                    })
                ])
            })
        ])
    })

1 个答案:

答案 0 :(得分:3)

Typescript是javascript之上漂亮的抽象层,保持了javascript的所有优势,例如功能范式,但例如通过使用静态类型的语言来弥补其弱点。

您需要的不是一组数组,而是另一组。检查initFormArray方法:

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

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
  title = "testAngular";

  formArray: FormArray;

  inputArray: Student[];
  constructor(
    private fb: FormBuilder,
  ) {}

  ngOnInit(): void {
    this.inputArray = [
      {
        type: "student",
        name: {
          first: "Nick",
          last: "Peru"
        },
        skills: [
          {
            title: "programming",
            desc: "Whatever"
          },
          {
            title: "design",
            desc: "Whatever"
          }
        ]
      }
    ];
  }

  initFormArry() {
    this.formArray = this.fb.array(
      this.inputArray.map((student) => this.fb.group({
        type: new FormControl(student.type),
        name: new FormGroup({
          first: new FormControl(student.name.first),
          last: new FormControl(student.name.last),
        }),
        skills: this.fb.array(student.skills.map((skill) => this.fb.group({
          title: new FormControl(skill.title),
          desc: new FormControl(skill.desc)
        })))
      }))
    );
  }
}

interface Student {
  type: string;
  name: {
    first: string;
    last: string;
  };
  skills:
      {
        title: string;
        desc: string;
      }[]
    ;
}