发送带有formArray值的输入值?

时间:2018-12-13 14:30:59

标签: html angular typescript input

我有一个FormArray,可以输入新字段并可以在单击按钮时发送整个表单的值,但是我试图添加一个input,该name与保存在相同的对象数据,但是我似乎无法让它与其他更新的数据一起显示发送...

Here is my blitz

html

<form [formGroup]="myForm">
    <div formArrayName="companies">
      <!-- I am wanting to update and send the name of the input also... -->
      <input formControlName="name"/>

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

.ts

export class AppComponent {

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

  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      companies: this.fb.array([])
    })

    this.setCompanies();
  }

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

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

  setCompanies() {
    let control = <FormArray>this.myForm.controls.companies;
    this.data.companies.forEach(x => {
      control.push(this.fb.group({ 
        name: x.name, 
        projects: this.setProjects(x) }))
    })
  }

  setProjects(x) {
    let arr = new FormArray([])
    x.projects.forEach(y => {
      arr.push(this.fb.group({ 
        projectName: y.projectName 
      }))
    })
    return arr;
  }

  submit(value) {
    console.log(value);
  }

}

1 个答案:

答案 0 :(得分:2)

由于您使用的是controlArray,因此您将需要在[formGroupName]="i"范围内移动输入,因为formControlName="name"[formGroupName]="i"的子代。

  <legend><h3>COMPANY {{i+1}}: </h3></legend>
        <div [formGroupName]="i">
              <input formControlName="name"/>