【问题标题】:How to populate FormArray inside Mat Table?如何在 Mat Table 中填充 FormArray?
【发布时间】:2021-03-02 18:20:38
【问题描述】:

我正在尝试使用FormArray 创建一个材料表。但问题是它没有设置formContolName。下面是我写的代码:

TS

form = this.fb.group({
  production: this.fb.array([this.initProductionForm()])
});

initProductionForm(): FormControl {
  return this.fb.control({
    proddate: [''], shift: [''], machine: [''], run: [''], operator: [''], helper: ['']
  });
}

createTable() {
  this.dataSource = new MatTableDataSource<any>((this.complaintForm.get('production') as FormArray).controls);
  this.dataSource.paginator = this.paginator;
}

ngOnInit() {
  this.createTable();
}

HTML

<form [formGroup]="form">
  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource">
      <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay; index as i">
        <th mat-header-cell *matHeaderCellDef>
          {{ 
            column == 'proddate' ? 'Date' : column == 'machine' ? 'Mach#' :
            column == 'run' ? 'Run#' : column
          }}
        </th>
        <td mat-cell *matCellDef="let element" [formGroup]="element">
          <input type="date" class="form-control tdfields" *ngIf="column=='proddate'" formControlName="proddate">
          <input class="form-control tdfields" *ngIf="column=='shift'" formControlName="shift">
          <input class="form-control tdfields" *ngIf="column=='machine'" formControlName="machine">
          <input class="form-control tdfields" *ngIf="column=='run'" formControlName="run">
          <input class="form-control tdfields" *ngIf="column=='operator'" formControlName="operator">
          <input class="form-control tdfields" *ngIf="column=='helper'" formControlName="helper">
        </td>
      </ng-container>
      <tr mat-header-row *matHeaderRowDef="columnsToDisplay; sticky: true"></tr>
      <tr mat-row *matRowDef="let element; columns: columnsToDisplay;"></tr>
    </table>
    <mat-paginator [pageSizeOptions]="[5, 1, 10, 20, 50, 100]" showFirstLastButtons></mat-paginator>
  </div>
</form>

我遵循了这个Stackblitz 示例。我得到的错误是:

谁能告诉我怎么解决? 我试过formGroupName 而不是formGroup 但仍然没有变化。 请帮帮我。

【问题讨论】:

    标签: angular typescript angular-material angular9 mat-table


    【解决方案1】:

    将输入包裹在&lt;mat-form-field&gt; 中,以便能够使用formControl 或formControlName。

    【讨论】:

    • 我不认为这是一个有效的答案,因为我已经在使用没有mat-form-field
    猜你喜欢
    • 2018-04-11
    • 2019-07-23
    • 1970-01-01
    • 2020-05-03
    • 2015-10-09
    • 2021-02-01
    • 2019-12-05
    • 2019-10-14
    • 2020-09-14
    相关资源
    最近更新 更多