Angular2 patchValue JSON数据到formArray

编程入门 行业动态 更新时间:2024-10-23 19:30:40
本文介绍了Angular2 patchValue JSON数据到formArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的Json数据:

I have a Json data like this:

assets/details.json

{ "name" : "john", "age" : 20, "address" : [{ "main": "address1", "sub": "address2" }, { "main": "add1", "sub": "add2" }] }

我想用 patchValue 以Angular形式显示所有这些JSON数据.

I want to show those all JSON data in Angular forms with patchValue.

我已经尝试过了.

appponent.ts

export class AppComponent { data: FormGroup constructor(private FB: FormBuilder, private service: DataService) { } ngOnInit() { this.data = this.FB.group({ name: [''], age: [''], address: this.FB.array([ this.addAddress() ]) }) this.getData() } addAddress(): FormGroup { return this.FB.group({ main: [''], sub: [''], }) } getData() { this.service.getData('../assets/details.json').subscribe((data) => { this.data.patchValue({ data }) } }

我已经这样设计HTML页面: appponent.html

And I've design my HTML page like this: appponent.html

<form [formGroup]="data" (ngSubmit)="onSubmit()"> <input formControlName="name" type="text" class="form-control col-sm-8"> <input formControlName="age" type="number" class="form-control col-sm-8"> <div formArrayName="address" *ngFor="let d of data.get('address').controls; let i = index;"> <div [formGroupName]="i"> <input formControlName="main" type="text" class="form-control"> <input formControlName="sub" type="text" class="form-control" /> </div> </div> </form>

但是没有什么能像我预期的那样工作.没有什么可以填满表格.我不知道该怎么做.

But nothing works as I expected. Nothing can fill up to the form. I don't know how to do further.

如何在表单字段中获取所有这些JSON数据?

How can I get all those JSON data in form fields?

推荐答案

如果您的表单中没有 FormArray ,则可以只使用 this.data.patchValue(data)(如果所有属性都匹配,则返回 setValue ),但是由于您有一个formarray,因此需要迭代对象中的 address 数组并将表单组推送到您的对象中formarray.另外,我认为在构建表单时不需要最初创建一个空的表单组,因此我将其省略了:

If you were not to have a FormArray in your form, you could just use this.data.patchValue(data) (or setValue if all properties match), but since you have a formarray, you need to iterate your address array in your object and push formgroups to your formarray. Also I see no need to initially create an empty formgroup when building the form, so I have left it out:

ngOnInit() { this.data = this.FB.group({ name: [''], age: [''], address: this.FB.array([]) }) } get formArr() { return this.data.get('address') as FormArray; } // .... this.data.patchValue({name: data.name, age: data.age}); data.address.forEach((x) => { this.formArr.push(this.FB.group(x)) });

更多推荐

Angular2 patchValue JSON数据到formArray

本文发布于:2023-11-15 10:32:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1593645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   patchValue   formArray   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!