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



我从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'
})
])
})
])
})

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

最新更新