I need help with inserting a new row in mat-table using a button. I wrote a function for this, but when I click the button, I encounter an error
CalculatoryBookingsComponent.html:62 ERROR Error: Cannot find control with path: 'rows -> 0'
. Additionally, only the first 5 cells are displayed. Can someone assist me in understanding and fixing this issue?
Here is where I'm working on it: https://stackblitz.com/edit/angular-l9x7ac?file=app%2Ftable-basic-example.html
Snippet of the code:
// HTML
<button class="crud-status" type="submit" mat-raised-button (click)="addRow()">add</button>
<td mat-cell *matCellDef="let row; let i = index;">
<div formArrayName="rows" *ngIf="attributesWithFormControls.includes(column.attribute); else otherColumns"> // Line 62: This is the area where the error code points to
<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
// ********** DATA TABLE ARRAYS **********//
private beforeMonthsColumns: EditColumns[] = [
{ attribute: 'name', name: 'Erlöse / Kostenarten', object: null, disabledRanges: false, disabledAssignment: false },
{ attribute: 'kagNumber', name: 'KAG', object: null, disabledRanges: false, disabledAssignment: false }
];
private monthColumns: EditColumns[] = [
{ attribute: '1', name: 'Jan', object: 'values', disabledRanges: false, disabledAssignment: false },
{ attribute: '2', name: 'Feb', object: 'values', disabledRanges: false, disabledAssignment: false },
{ attribute: '3', name: 'Mrz', object: 'values', disabledRanges: false, disabledAssignment: false }
];
private afterMonthsColumns: EditColumns[] = [
{ attribute: 'note', name: 'Anmerkung', object: null, disabledRanges: false, disabledAssignment: false },
{ attribute: 'assignment', name: 'zugeordnet? KAG', object: null, disabledRanges: false, disabledAssignment: true }
];
// Merged arrays
public displayedColumns: EditColumns[] = [
...this.beforeMonthsColumns,
...this.monthColumns,
...this.afterMonthsColumns
];
addRow() {
this.dataSource.data.push(this.columns[this.index++])
this.table.renderRows()
}
const formRowsData = [];
const nameFormArray = this.calcBookingsForm.get('rows') as FormArray;
// build form array values for text fields in data table rows
for (const formRowDataEntry of formRowsData) {
const consolidatedValues = {};
// Combine rows values into one object
for (const d of formRowDataEntry) {
consolidatedValues[d.attr] = d.value;
}
// bind values of one row to a form control group
const rowGroup = this.formBuilder.group(consolidatedValues);
nameFormArray.push(rowGroup);
rowGroup.valueChanges.subscribe((rowData) => {
console.log('Row data changed:', rowData);
});
}
this.dataSource.data = rows;