我有一个像这样的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
发布评论