[英]Simple way to convert an multidimensional array to formGroup
I get a multidimensional array from API to edit data.我从 API 得到一个多维数组来编辑数据。 Now I want to convert that array in angular
formgroup
.现在我想在 angular
formgroup
中转换该数组。
I've tried loop, nested loop for converting that array in formGroup
.我试过循环,嵌套循环来转换
formGroup
中的数组。 But I thought there should have an easy way但我认为应该有一个简单的方法
Suppose I've data like:假设我有如下数据:
const arr = [
{
type: 'student',
name: {
first: 'Nick',
last: 'Peru'
},
skills: [
{
title: 'programming',
desc: 'Whatever'
},
{
title: 'design',
desc: 'Whatever'
}
]
},
...
]
I want something like this我想要这样的东西
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 is a beautiful abstraction layer on top of javascript, keeping all the strength of javascript eg the functional paradigm but covering its weaknesses by for example being a statically typed language. Typescript 是 javascript 之上的一个漂亮的抽象层,保留了 javascript 的所有优点,例如功能范式,但通过例如静态类型语言来弥补其弱点。
What you need is not a group of arrays but the other way around.您需要的不是一组 arrays,而是相反。 Check the initFormArray method:
检查 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; }[]; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.