mat-table 中的表单数组中不显示新行

New row is not displayed in the form array in mat-table

我在我的 mat-table 中使用了一个表单数组,我想通过单击添加按钮向 table 添加一个新行。我为此写了逻辑。但是什么也没有给我看。你能告诉我我的错误在哪里以及如何解决吗?

我的代码:

// HTML

<!-- Add rows -->
<button type="submit" mat-raised-button (click)="addRow()">add</button>

<!-- Table-Content -->
              <td mat-cell *matCellDef="let row; let i = index;">
                <div formArrayName="rows" *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns">
                  <span class="edit-cell" [formGroupName]="i">
                      <mat-form-field>
                        <label>
                          <input matInput type="text" [formControlName]="column.attribute">
                        </label>
                      </mat-form-field>
                  </span>
                </div>
                <ng-template #otherColumns>
                  {{ column.object  !== null ? row[column.object][column.attribute] : row[column.attribute]  }}
                </ng-template>
              </td>

// TS

// For the form
calcBookingsForm: FormGroup;

// Variables for Data Table
  public columns = [];
  public dataSource: MatTableDataSource<MyModel> = null;

public displayedColumns: EditColumns[] = [
{ attribute: 'firstName', name: 'Firstname', object: null },
{ attribute: 'secondName', name: 'Lastname', object: null }
];

// Attributes defined here are displayed as input in the front end
public attributesWithFormControls = ['firstName', 'secondName'];

 ngOnInit(): void {
this.columns = this.displayedColumns.map(c => c.attribute);

 // CalcBookings form
    this.calcBookingsForm = this.formBuilder.group({
      rows: this.formBuilder.array([this.initItemRows()])
    });
}

 get formArr() {
    return this.calcBookingsForm.get('rows') as FormArray;
  }

  initItemRows() {
    return this.formBuilder.group({
      firstName: [''],
      lastName: [''],
    });
  }

// To add new row in the CalculatoryBookings
  addRow() {
    this.formArr.push(this.initItemRows())
  }

列表示行中的数据类型,因此向 table 添加行就像添加一条空记录。这取决于您在输入数据时要对新行中的数据执行的操作,您必须在保存新数据时为该行的行为添加另一个逻辑,在此示例中,我将教授如何添加新行。 Html 文件 table 和一键添加行:

<div style="margin-top: 64px; margin-left: 64px;">
    <button (click)="AddRow()" mat-raised-button>Add</button>
</div>

<div style="margin-top: 64px;"></div>
<table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8">
    <ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
        <th mat-header-cell *matHeaderCellDef> {{column}} </th>

        <td mat-cell *matCellDef="let element">
            <mat-form-field>
                <input matInput [value]="element[column]" />
            </mat-form-field>
        </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
    <tr mat-row *matRowDef="let element; columns: columnsToDisplay;">
    </tr>
</table>

Class 您要添加的数据:

export interface ProductElement {
  name: string;
  id: string;
  color: string;
  year: number;
  price: number;
}

使用示例数据创建行的数据:

// List of Brands
  brands: string[] = ['Vapid', 'Carson', 'Kitano', 'Dabver', 'Ibex', 'Morello', 'Akira', 'Titan', 'Dover', 'Norma'];
  // List of Colors
  colors: string[] = ['Black', 'White', 'Red', 'Blue', 'Silver', 'Green', 'Yellow'];
  // Column definition
  columnsToDisplay: string[] = ['id', 'name', 'year', 'color', 'price'];
  dataSource: MatTableDataSource<ProductElement>;

创建随机数据的方法:

generateName = () => {
    return this.brands[Math.floor(Math.random() * Math.floor(10))];
  }

  generatePrice = () => {
    return Math.floor(Math.random() * Math.floor(50000) + 1);
  }

  generateColor = () => {
    return this.colors[Math.floor(Math.random() * Math.floor(7))];
  }

  generateYear = () => {
    return 2000 + Math.floor(Math.random() * Math.floor(19));
  }

  createId(): string {
    let id = '';
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < 5; i++) {
      id += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return id;
  }

添加新行的方法:

newRow = () => {
    const data = {
      id: this.createId(),
      name: this.generateName(),
      year: this.generateYear(),
      color: this.generateColor(),
      price: this.generatePrice(),
    };
    return data;
  }

以及使用示例数据添加新行的方法。

AddRow(): void {
    ELEMENT_DATA.push(this.newRow());
    this.dataSource = new MatTableDataSource<ProductElement>(ELEMENT_DATA);
  }

最终结果:

练习一下,你会告诉我它是怎么回事。 更新: 在您的示例中,如果您更改 Add 方法,如下所示 结果: