需要创建角度为6的动态表格

时间:2018-12-12 07:09:42

标签: angular angular-reactive-forms

https://stackblitz.com/edit/angular-h2syhv?file=src%2Fapp%2Fapp.component.ts

我的要求是创建一个带有formFields数组的表单,该表单是我为formfields创建的对象并已推送到formgroup的表单字段列表,但是我认为我错过了UI中结构不正确的地方formfields不正确我在Stackblit中更新了代码 谢谢我

Console error you can check this is image url here

1 个答案:

答案 0 :(得分:0)

我发现您的实施存在很多问题。所以我决定创建自己的。

您要寻找的是用FormArray个创建一个FormGroup,其中每个FormGroup都有FormControl个动态创建的。

为此,您可以这样编写组件类:

import { Component, OnInit, Input, SimpleChanges, OnChanges } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  formFields = [ ... ];

  public tablesForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.tablesForm = this.fb.group({
      employees: this.fb.array([this.addEmployerDetails()])
    });
  }

  addEmployerDetails() {
    const employeeDetailsFormGroup = this.fb.group({});
    this.formFields.forEach(field => {
      employeeDetailsFormGroup.addControl(field.formControl, this.fb.control([]));
    });
    return employeeDetailsFormGroup;
  }

  addEmployerToFormArray() {
    this.employeeRows.push(this.addEmployerDetails());
  }

  get employeeRows() {
    return (<FormArray>this.tablesForm.get('employees'));
  }

}

我们正在FormGroup中创建ngOnInit,在此我们还调用addEmployerDetails,它会基于FormGroup返回formFields

addEmployerToFormArray会为您的FormGroup tablesForm添加一个新的FormGroup,并且会在Add Employer div单击时从模板中调用。

employeeRows get er还将在Template和Component Class本身中使用。

在您的模板中:

<div class="form-group">
    <div class="row pad-leftright">
        <div class="col-md-12">
            <div (click)="addEmployerToFormArray()">
                <span><i class="fa fa-plus plus-icon"></i></span>
        <span class="emp-title">Add Employer</span>
      </div>
    </div>
  </div>
  <form [formGroup]="tablesForm">
    <div class="row pad-leftright">
      <div>
        <table class="table ft-table simple-table table-equal-columns" border="1">
          <thead class="theader">
            <tr>
              <th *ngFor="let x of formFields">{{x.name}}</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let row of employeeRows.controls; let ind = index;">
              <td formArrayName="employees" *ngFor="let field of formFields">
                <div [formGroupName]="ind">
                  <div>
                    <div class="form-group">
                      <input [type]="field.type" class="form-control" id="example-input-3" [placeholder]="field.name" [formControlName]="field.formControl" />
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </form>
</div>

这是您推荐的Working Sample StackBlitz