带有嵌套表单数组的角反应表单 [英] Angular Reactive Forms with nested Form Arrays

查看:91
本文介绍了带有嵌套表单数组的角反应表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular 2的新手,因此决定最好的学习方法是阅读Angular官方指南.

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

我仔细阅读了《反应式指南》 https://angular.io/guide/reactive-forms

I went through the Reactive Forms Guide https://angular.io/guide/reactive-forms

演示链接: https://stackblitz.com/angular/jammvmbrpxle

虽然内容总体来说还不错,但我仍坚持如何实现更复杂的表单.在给定的示例中,每个英雄都有很多地址的潜力.地址本身就是一个平面对象.

While the content was overall pretty good, I'm stuck on how I would go about implementing a more complex Form. In the given example, each Hero has the potential for many addresses. An address itself is a flat object.

如果地址"有其他信息,例如位于该地址的房间的颜色和类型,该怎么办?

What if Addresses had additional information such as the color and type of rooms located at the address.

export class Address {
    street = '';
    city   = '';
    state  = '';
    zip    = '';
    rooms = Room[];
}

export class Room {
     type = '';
}

以便表单模型如下所示……

so that the form model would look like this...

createForm() {
this.heroForm = this.fb.group({
  name: '',
  secretLairs: this.fb.array([
      this.fb.group({
          street: '',
          city: '',
          state: '',
          zip: '',
          rooms: this.fb.array([
              this.fb.group({
                 type: ''
          })]),
      })]),
  power: '',
  sidekick: ''
});

}

编辑-与ngOnChanges一起使用的最终代码

hero-detail.component.ts

hero-detail.component.ts

createForm() {
    this.heroForm = this.fb.group({
      name: '',
      secretLairs: this.fb.array([
        this.fb.group({
          street: '',
          city: '',
          state: '',
          zip: '',
          rooms: this.fb.array([
            this.fb.group({
              type: ''
            })
          ])
        })
      ]),
      power: '',
      sidekick: ''
    });
  }

  ngOnChanges() {
    this.heroForm.reset({
      name: this.hero.name,
    });
    this.setAddresses(this.hero.addresses);
  }

  setAddresses(addresses: Address[]) {
    let control = this.fb.array([]);
    addresses.forEach(x => {
      control.push(this.fb.group({
        street: x.street,
        city: x.city,
        state: x.state,
        zip: x.zip,
        rooms: this.setRooms(x) }))
    })
    this.heroForm.setControl('secretLairs', control);
  }

  setRooms(x) {
    let arr = new FormArray([])
    x.rooms.forEach(y => {
      arr.push(this.fb.group({ 
        type: y.type 
      }))
    })
    return arr;
  }

hero-detail.component.html(嵌套表单数组部分)

hero-detail.component.html (the nested form array portion)

<div formArrayName="secretLairs" class="well well-lg">
  <div *ngFor="let address of heroForm.get('secretLairs').controls; let i=index" [formGroupName]="i" >
    <!-- The repeated address template -->
    <h4>Address #{{i + 1}}</h4>
    <div style="margin-left: 1em;">
      <div class="form-group">
        <label class="center-block">Street:
          <input class="form-control" formControlName="street">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">City:
          <input class="form-control" formControlName="city">
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">State:
          <select class="form-control" formControlName="state">
            <option *ngFor="let state of states" [value]="state">{{state}}</option>
          </select>
        </label>
      </div>
      <div class="form-group">
        <label class="center-block">Zip Code:
          <input class="form-control" formControlName="zip">
        </label>
      </div>
    </div>
    <br>
    <!-- End of the repeated address template -->
    <div formArrayName="rooms" class="well well-lg">
      <div *ngFor="let room of address.get('rooms').controls; let j=index" [formGroupName]="j" >
          <h4>Room #{{j + 1}}</h4>
          <div class="form-group">
            <label class="center-block">Type:
              <input class="form-control" formControlName="type">
            </label>
          </div>
      </div>
    </div>
  </div>
  <button (click)="addLair()" type="button">Add a Secret Lair</button>
</div>

推荐答案

拥有嵌套的formarray并没有太大区别.基本上,您只是复制带有嵌套数组的代码... :)因此,这是一个示例:

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 = <FormArray>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 = <FormArray>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)
}

以相同的方式使用模板,对外部formarray进行迭代,然后在内部对内部form数组进行迭代:

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

<form [formGroup]="myForm">
  <div formArrayName="companies">
    <div *ngFor="let comp of myForm.get('companies').controls; let i=index">
    <h3>COMPANY {{i+1}}: </h3>
    <div [formGroupName]="i">
      <input formControlName="company" />
      <button (click)="deleteCompany(i)">
         Delete Company
      </button>
      <div formArrayName="projects">
        <div *ngFor="let project of comp.get('projects').controls; let j=index">
          <h4>PROJECT {{j+1}}</h4>
          <div [formGroupName]="j">
            <input formControlName="projectName" />
            <button (click)="deleteProject(comp.controls.projects, j)">
              Delete Project
            </button>
          </div>
        </div>
        <button (click)="addNewProject(comp.controls.projects)">
          Add new Project
        </button>
      </div>
    </div>
  </div>
</div>

要在拥有数据后为表单设置值,可以调用以下方法来迭代数据并为表单设置值.在这种情况下,data看起来像:

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",
        }
      ]
    }
  ]
}

我们调用setCompanies将值设置为表单:

We call setCompanies to set values to our form:

setCompanies() {
  let control = <FormArray>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;
}

这篇关于带有嵌套表单数组的角反应表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆