Angular Reactive Forms with nested Form Arrays

前端 未结 3 1420
执念已碎
执念已碎 2020-11-28 21:01

I\'m new to Angular 2 and decided the best way to learn would be to go through the official Angular guides.

I went through the Reactive Forms Guide https://angular.i

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 21:14

    It's not very much different to have a nested formarray. Basically you just duplicate the code you have... with nested array :) So here's a sample:

    myForm: FormGroup;
    
    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        // you can also set initial formgroup inside if you like
        companies: this.fb.array([])
      })
    }
    
    addNewCompany() {
      let control = this.myForm.controls.companies;
      control.push(
        this.fb.group({
          company: [''],
          // nested form array, you could also add a form group initially
          projects: this.fb.array([])
        })
      )
    }
    
    deleteCompany(index) {
      let control = this.myForm.controls.companies;
      control.removeAt(index)
    }
    

    So that is the add and delete for the outermost form array, so adding and removing formgroups to the nested form array is just duplicating the code. Where from the template we pass the current formgroup to which array you want to add (in this case) a new project/delete a project.

    addNewProject(control) {
      control.push(
        this.fb.group({
          projectName: ['']
      }))
    }
    
    deleteProject(control, index) {
      control.removeAt(index)
    }
    

    And the template in the same manner, you iterate your outer formarray, and then inside that iterate your inner form array:

    COMPANY {{i+1}}:

    PROJECT {{j+1}}

    DEMO

    EDIT:

    To set values to your form once you have data, you can call the following methods that will iterate your data and set the values to your form. In this case data looks like:

    data = {
      companies: [
        {
          company: "example comany",
          projects: [
            {
              projectName: "example project",
            }
          ]
        }
      ]
    }
    

    We call setCompanies to set values to our form:

    setCompanies() {
      let control = this.myForm.controls.companies;
      this.data.companies.forEach(x => {
        control.push(this.fb.group({ 
          company: x.company, 
          projects: this.setProjects(x) }))
      })
    }
    
    setProjects(x) {
      let arr = new FormArray([])
      x.projects.forEach(y => {
        arr.push(this.fb.group({ 
          projectName: y.projectName 
        }))
      })
      return arr;
    }
    

提交回复
热议问题