如何在angular2中实现嵌套数据形式 [英] How to implement nested data form in angular2

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

问题描述

这里是 Json 架构:

<代码>{"_id" : ObjectId("59031d77fd5e1c0b3c005d15"),简历数据":{工作经验" : [{公司":示例",网站":example.com","职位" : "实习","highlights" : "学习在 Laravel 框架中创建 API.同时学习 Angular 2 进行前端开发.",项目经验" : [{"projectName": "Facebook 项目","teamMember" : "5","技术": "PHP,Laravel-5,Angular-2,MongoDb","projectPosition" : "后端开发人员"}]}]}}

这是图片:

我参考了这个答案 但我不知道嵌套表单数据.谁能解释一下如何实现它.

解决方案

这是你的代码,它设置你从后端接收的数据,这里我将它存储在一个变量 data 中.

请注意,这是您表单的简化版本,但基础已经存在,您只需要在相应的表单数组中添加几个缺失的属性即可.

空表单的构建看起来只是一个名为 work_experienceFormArray 匹配您的 json 结构:

this.myForm = this.fb.group({工作经验:this.fb.array([])})

我们在接收数据时添加字段,在接收数据的回调中调用setWorkExperience函数:

setWorkExperience(){//获取表单数组让 control = this.myForm.controls.work_experience;//从您的 JSON 中迭代数组 'work_experience' 并推送具有属性和内部表单数组的新表单组this.data.work_experience.forEach(x => {//在下面添加其余的属性control.push(this.fb.group({company: x.company, project_experience: this.setFormArray(x)}))})}

setFormArray 是从前面的函数中调用的,在这里我们用 from project_experience 将数据修补到内部表单数组中:

setFormArray(x) {//创建本地数组,该数组返回 JSON 中project_experience"中的所有值让 arr = new FormArray([])x.project_experience.map(y => {//在下面添加其余的属性arr.push(this.fb.group({projectName: y.projectName}))})返回 arr;}

模板将如下所示:

<!-- 迭代的最外层数组--><div formArrayName="work_experience"><div *ngFor="let a of myForm.get('work_experience').controls; let i=index"><h3>公司{{i+1}}:</h3><div formGroupName="{{i}}"><label>公司名称:</label><input formControlName="company"/><span><button (click)="deleteCompany(i)">删除公司</button></span><br><br><!-- 内部表单数组迭代--><div formArrayName="project_experience"><div *ngFor="let b of myForm.controls.work_experience.controls[i].controls.project_experience.controls; let j=index"><h4>项目{{j+1}}</h4><div formGroupName="{{j}}"><label>项目名称:</label><input formControlName="projectName"/><span><button (click)="deleteProject(a.controls.project_experience, j)">删除项目</button></span>

<button (click)="addNewProject(a.controls.project_experience)">添加新项目</button>

</表单>

在模板中,您可以看到用于添加和删除项目和公司的按钮.添加和删​​除公司很简单,其中 initCompany() 返回一个 formGroup:

deleteCompany(index) {让 control = <FormArray>this.myForm.controls.work_experience;control.removeAt(index)}添加新公司(){让 control = <FormArray>this.myForm.controls.work_experience;control.push(this.initCompany())}

在添加项目中,我们从模板中将当前 formArray 控件作为参数传递给该控件,我们只是将一个新的 FormGroup 推送到该控件中:

addNewProject(control) {control.push(this.initProject())}

在删除函数中,我们传递当前的表单数组以及我们要删除的项目的索引:

deleteProject(control, index) {control.removeAt(index)}

这应该涵盖几乎所有内容.

Plunker

Here is Json schema :

{
    "_id" : ObjectId("59031d77fd5e1c0b3c005d15"),

    "resume_data" : {

     "work_experience" : [ 
            {
                "company" : "example",
                "website" : "example.com",
                "position" : "Internship",
                "highlights" : "Learn To Create API In Laravel Framework. and also Learn Angular 2 for Front end Development.",
                "project_experience" : [ 
                    {
                        "projectName" : "Fb Project",
                        "teamMember" : "5",
                        "technology" : "PHP,Laravel-5,Angular-2,MongoDb",
                        "projectPosition" : "Back-end Developer"
                    }
                ]
            }
        ]

   }
}

Here is image:

I have reference of this answer but i don't know about nested form data. can anyone explain how to implement it.

解决方案

Here is your code, which sets the data you are receiving from backend, here I have stored it in a variable data.

Please notice, this is a shortened version of your form, but the basics are there, you only need to add the few missing properties in corresponding form arrays.

The build of the empty form looks is just a FormArray named work_experience matching your json structure:

this.myForm = this.fb.group({
  work_experience: this.fb.array([])
})

We add the fields when you are receiving the data, call a function called setWorkExperience in the callback when receiving data:

setWorkExperience(){
  // get the formarray
  let control = <FormArray>this.myForm.controls.work_experience;
  // iterate the array 'work_experience' from your JSON and push new formgroup with properties and the inner form array
  this.data.work_experience.forEach(x => {
    // add the rest of your properties also below
    control.push(this.fb.group({company: x.company, project_experience: this.setFormArray(x)}))
  })
}

setFormArray is called from the previous function, where we patch the data with from project_experience to the inner form array:

setFormArray(x) {
  // create local array which is returned with all the values from the 'project_experience' from your JSON
  let arr = new FormArray([])
  x.project_experience.map(y => {
    // add the rest of your properties below
    arr.push(this.fb.group({projectName: y.projectName}))
  })
  return arr;
}

The template would then look like this:

<form [formGroup]="myForm">
  <!-- Outmost array iterated -->
  <div formArrayName="work_experience">
    <div *ngFor="let a of myForm.get('work_experience').controls; let i=index">
      <h3>COMPANY {{i+1}}: </h3>
      <div formGroupName="{{i}}">
        <label>Company Name: </label>
        <input formControlName="company" /><span><button (click)="deleteCompany(i)">Delete Company</button></span><br><br>
        <!-- inner formarray iterated -->
        <div formArrayName="project_experience">
          <div *ngFor="let b of myForm.controls.work_experience.controls[i].controls.project_experience.controls; let j=index">
            <h4>PROJECT {{j+1}}</h4>
            <div formGroupName="{{j}}">
              <label>Project Name:</label>
              <input formControlName="projectName" /><span><button (click)="deleteProject(a.controls.project_experience, j)">Delete Project</button></span>
            </div>
          </div>
          <button (click)="addNewProject(a.controls.project_experience)">Add new Project</button>
        </div>
      </div>
    </div>
  </div>   
</form>

In the template you can see the buttons for add and delete of projects and companies. Adding and deleting companies are straightforward, where initCompany() returns a formGroup:

deleteCompany(index) {
  let control = <FormArray>this.myForm.controls.work_experience;
  control.removeAt(index)
}

addNewCompany() {
  let control = <FormArray>this.myForm.controls.work_experience;
  control.push(this.initCompany())
}

In the add project we pass as parameter from the template the current formArray control, to which we just push a new FormGroup:

addNewProject(control) {
  control.push(this.initProject())
}

In the delete function we pass the current formarray as well as the index of the project we want to delete:

deleteProject(control, index) {
  control.removeAt(index)
}

That should cover pretty much everything.

Plunker

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

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