我已经在mat-table的帮助下在Angular中创建了一个动态表,现在我想向其添加反应形式,但是我无法将其放置到位。我想我需要使用formArrayName。
HTML组件代码:
<form [formGroup]="form">
<mat-table
class="xsm-LaborOutputDrawerTable"
#table
[dataSource]="items"
[formArrayName]="actualsVolumeData">
<ng-container
*ngFor="let column of columns; let i=index"
[stickyEnd]="i === columns.length-1 ? true : false"
[matColumnDef]="column.columnId">
<mat-header-cell *matHeaderCellDef mat-sort-header> {{column.label}} </mat-header-cell>
<mat-cell
[ngClass]="{'xsm-LaborOutputDrawerTable-settingCode': !i }"
[formGroupName]="i"
*matCellDef="let element">
<mat-form-field *ngIf="!!i && i < columns.length - 1" appearance="legacy" >
<!-- [value]="element[column.columnId]" -->
<input matInput
class="xsm-LaborOutputDrawerTable-input"
formControlName ="element.column"
>
<mat-icon *ngIf="i === 1" matSuffix>done</mat-icon>
</mat-form-field>
<span *ngIf="!i">
{{element[column.columnId]}}
</span>
<button
mat-button
*ngIf="i === columns.length-1"
(click)="onResetRowClick(element)">
<mat-icon>close</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="columnFields"></mat-header-row>
<mat-row *matRowDef="let row; columns: columnFields;"></mat-row>
</mat-table>
</form>
在组件代码中,我有这个:
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'xlm-labor-model-output-drawer-table',
templateUrl: './labor-model-output-drawer-table.component.html',
styleUrls: ['./labor-model-output-drawer-table.component.scss'],
})
export class LaborModelOutputDrawerTableComponent implements OnInit {
items: any[] = [];
columnFields: any[];
columns = [{ columnId: 'settingName', label: '' }, { columnId: 'applyToWeeks', label: 'Apply to all Weeks' }];
// columns: any;
rows: FormArray = this.fb.array([]);
form: FormGroup = this.fb.group({ actualsVolumeData: this.rows });
@Input() gridSource: any = [];
@Input() dataSource: any;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.getDisplayedColumns();
this.form = this.fb.group({
columns: this.columns,
});
}
getDisplayedColumns(): any {
this.columns = this.columns.concat(this.dataSource.columnInfo.map((col) => ({ columnId: col.headerName, label: col.headerName })));
this.columns.push({ columnId: 'actions', label: 'Actions' });
this.columnFields = [...this.columns.map((x) => x.columnId)];
this.items = this.gridSource.settings.map((setting) => {
const row = {};
this.dataSource.columnInfo.forEach((column, idx) => {
row['settingName'] = setting.settingDisplayName;
row['applyToWeeks'] = setting.settingDisplayName;
row[column.headerName] = setting.weekData[idx].value;
row['applyToWeeks'] = 0;
});
return row;
});
}
onResetRowClick(row): void {
const keys = Object.keys(row);
const a = ['applyToWeeks', 'applyToWeeks', 'settingName'];
keys.forEach((key) => {
if (!a.includes(key)) {
row[key] = 0;
}
});
}
}
你们对此有什么解决方案? 我看到了一些替代词,但它们都很混乱。