如何在angular2的表单数组中显示嵌套数组数据? [英] How can display nested array data in form array in angular2?

查看:38
本文介绍了如何在angular2的表单数组中显示嵌套数组数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 angular2 项目中实现了 FormGroup 来渲染表单,并且我已经使用 formArray 来获取嵌套数组数据

form.component.html

<div *ngFor="let social of resumeForm.controls.social_profiles.controls; let i=index" class="panel panel-default m-t-10"><div class="panel-heading" style="min-height: 30px;"><span class="glyphicon glyphicon-remove pull-right" *ngIf="resumeForm.controls.social_profiles.controls.length > 1" (click)="removeSocialProfiles(i)"></span>

<div class="panel-body" [formGroupName]="i"><social-profile [group]="resumeForm.controls.social_profiles.controls[i]"></social-profile>

form.component.ts

导出类 FormComponent 实现 OnInit {公共简历表格:FormGroup;构造函数(私有 formBuilder:FormBuilder){}ngOnInit() {this.resumeForm = this.formBuilder.group({名称:['', Validators.required],标签: ['',],电子邮件: [''],电话: [''],social_profiles: this.formBuilder.array([])});this.addSocialProfiles();}initSocialProfiles() {返回 this.formBuilder.group({网络: [''],网址:['']});}addSocialProfiles() {const control = <FormArray>this.resumeForm.controls['social_profiles'];const addrCtrl = this.initSocialProfiles();control.push(addrCtrl);}removeSocialProfiles(i: number) {const control = <FormArray>this.resumeForm.controls['social_profiles'];control.removeAt(i);}}

其中 social-profile 是数组的子表单

social-profile.component.html

<div class="col-md-6"><input type="text" class="form-control" placeholder="输入网络" formControlName="network">

<div class="col-md-6"><input type="text" class="form-control" placeholder="输入网络URL" formControlName="url">

social-profile.component.ts

导出类 SocialProfileComponent {@Input('组')公共社交表单:FormGroup;}

从服务回调中获取 JSON

<代码>{基本信息":{"name": "周杰伦","label": "程序员",Social_profiles":[{"网络": "推特","url": "https://www.twitter.com/kumarrishikesh12"}, {"网络": "脸书","url": "https://www.facebook.com/kumarrishikesh12"}]}}

添加数据表单工作完美,但如何在页面初始化编辑时以表单显示现有的 json 嵌套数组(从 api 获取)?如下图

解决方案

这里假设您已经从对象 basics_info 中提取了内容,即:

并将JSON分配给一个变量data,这样你就得到了data的这个内容:

{"name": "周杰伦","label": "程序员",Social_profiles":[{"网络": "推特","url": "https://www.twitter.com/kumarrishikesh12"}, {"网络": "脸书","url": "https://www.facebook.com/kumarrishikesh12"}]}

然后让我们修补这些值.您可以在收到数据后收到 JSON(或构建表单)后修补这些值.在这里,我在构建表单后修补值.

下面我想澄清一下,调用 patchValues 中的另一个方法,它实际上设置了值.

patchValues() {const control = <FormArray>this.resumeForm.controls['social_profiles'];this.data.Social_profiles.forEach(x => {//迭代数组control.push(this.patch(x.network, x.url))//推送值});}补丁(网络,网址){返回 this.fb.group({网络:[网络],网址:[网址]});}

孩子应该能很好地捕捉到这些变化.这是给您的演示,变量不同,因为我使用了现有的表单.但逻辑是完全一样的.

Plunker

I have implemented FormGroup in angular2 project to render form and i have used formArray for getting nested array data

form.component.html

<div class="col-md-12" formArrayName="social_profiles">
  <div *ngFor="let social of resumeForm.controls.social_profiles.controls; let i=index" class="panel panel-default m-t-10">
    <div class="panel-heading" style="min-height: 30px;">
      <span class="glyphicon glyphicon-remove pull-right" *ngIf="resumeForm.controls.social_profiles.controls.length > 1" (click)="removeSocialProfiles(i)"></span>
    </div>
    <div class="panel-body" [formGroupName]="i">
      <social-profile [group]="resumeForm.controls.social_profiles.controls[i]"></social-profile>
    </div>
  </div>
</div>

form.component.ts

export class FormComponent implements OnInit {
    public resumeForm: FormGroup;

    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
        this.resumeForm = this.formBuilder.group({
            name: ['', Validators.required],
            label: ['',],
            email: [''],
            phone: [''],  
            social_profiles: this.formBuilder.array([])
        });

        this.addSocialProfiles();
    }

    initSocialProfiles() {
        return this.formBuilder.group({
            network: [''],
            url: ['']
        });
    }

    addSocialProfiles() {
        const control = <FormArray>this.resumeForm.controls['social_profiles'];
        const addrCtrl = this.initSocialProfiles();        
        control.push(addrCtrl);      
    }

    removeSocialProfiles(i: number) {
        const control = <FormArray>this.resumeForm.controls['social_profiles'];
        control.removeAt(i);
    }
}

Where social-profile is child form for array

social-profile.component.html

<div [formGroup]="socialForm">
    <div class="col-md-6">
        <input type="text" class="form-control" placeholder="Enter Network" formControlName="network">
    </div>
    <div class="col-md-6">
        <input type="text" class="form-control" placeholder="Enter Network URL" formControlName="url">
    </div>
</div>

social-profile.component.ts

export class SocialProfileComponent {
    @Input('group')
    public socialForm: FormGroup;
}

Get JSON from Service callback

{
    "basics_info": {
        "name": "Joh Doe",
        "label": "Programmer",
        "Social_profiles": [{
            "network": "Twitter",
            "url": "https://www.twitter.com/kumarrishikesh12"
        }, {
            "network": "Facebook",
            "url": "https://www.facebook.com/kumarrishikesh12"
        }]
    }
}

Add data Form working perfect but how can i display existing nested array of json (which is get from api) in form on edit time on page init ? Like below image

解决方案

Here let's assume you have extracted the content from the object basics_info, i.e:

and assigned the JSON to a variable data, so that you end up with this content of data:

{
    "name": "Joh Doe",
    "label": "Programmer",
    "Social_profiles": [{
        "network": "Twitter",
        "url": "https://www.twitter.com/kumarrishikesh12"
    }, {
        "network": "Facebook",
        "url": "https://www.facebook.com/kumarrishikesh12"
    }]
}

Then let's patch the values. You can patch the values after you have received the JSON (or build the form) after receiving data. Here I patch values after form has been built.

Below I like for clarification call another method inside patchValues, which actually sets the values.

patchValues() {
  const control = <FormArray>this.resumeForm.controls['social_profiles'];
  this.data.Social_profiles.forEach(x => { // iterate the array
     control.push(this.patch(x.network, x.url)) // push values
  });
}

patch(network, url) {
  return this.fb.group({
    network: [network],
    url: [url]
  });
}

The child should catch these changes just fine. Here's a demo for you, the variables are different, since I used an existing form I had. But the logic is absolutely the same.

Plunker

这篇关于如何在angular2的表单数组中显示嵌套数组数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆