Array of formGroup within mat-table for each row

后端 未结 1 1334
情话喂你
情话喂你 2020-12-02 00:55

I have an array of formGroup, where each element represents a form. Next I have a mat table, where what I want to do is to generate each tr (so each row) as a distinct form,

相关标签:
1条回答
  • 2020-12-02 01:27

    It's difficult help if we can't get access to the code.

    In this stackblitz I put a simple example. See that we create a form Array like

    myformArray = new FormArray([
        new FormGroup({
          name: new FormControl("uno"),
          surname: new FormControl("one")
        }),
        new FormGroup({
          name: new FormControl("dos"),
          surname: new FormControl("two")
        }),
        new FormGroup({
          name: new FormControl("tres"),
          surname: new FormControl("three")
    
        })])
    

    The dataSource of the table is the formArray controls.

      dataSource = this.myformArray.controls;
    

    In this way, "element" is a FormGroup, so a cell can be like

      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element">
           <input [formControl]="element.get('name')">
           </td>
      </ng-container>
    

    See that we use [formControl]. That's. A mat-table iterate over myformArray.controls, that is only an array of FormGroups. The FormGroup is this "element", so element.get('...') is a FormControl. It's the reason we can use [formControl]=element.get('...')

    it's like we write not mat-table

    <div *ngFor="let element of myformArray.controls">
      <input [formControl]="element.get('name')">
      <input [formControl]="element.get('surname')">
    </div>
    
    0 讨论(0)
提交回复
热议问题