I'm trying to create an angular material table with reactive form. I need to add some properties, so I'm using formArray. But my table is not showing any result, and angular keeps me returning the same error:
ERROR TypeError: Cannot read properties of undefined (reading 'headerCell')
This is what I got until now:
HTML
<button mat-button mat-raised-button (click)="addParameterWhatsApp()" color="primary">Add</button>
<form [formGroup]="form" autocomplete="off">
<table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8" formGroupName="whatsapp">
<ng-container formArrayName="parameters">
<ng-container *ngFor="let dados of parameters.controls; let i = index ">
<div [formGroupName]="i">
<ng-container matColumnDef="posicao">
<th mat-header-cell *matHeaderCellDef> Posicao </th>
<td mat-cell *matCellDef="let element">
<mat-form-field appearance="outline">
<mat-label>Posicao</mat-label>
<input matInput formControlName="posicao">
</mat-form-field>
</td>
</ng-container>
<ng-container matColumnDef="valor">
<th mat-header-cell *matHeaderCellDef>Valor</th>
<td mat-cell *matCellDef="let element">
<mat-form-field appearance="outline">
<mat-label>Valor</mat-label>
<input matInput formControlName="valor">
</mat-form-field>
</td>
</ng-container>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</form>
TS
form!: FormGroup;
dataSource;
displayedColumns = ['posicao', 'valor'];
constructor(private _formBuilder: FormBuilder) {}
ngOnInit(): void {
this.createForm();
}
createForm() {
this.form = this._formBuilder.group({
whatsapp: this._formBuilder.group({
name: [],
parameters: this.buildArrayParametersWhatsApp(),
}),
});
}
get parameters() {
return this.form.get('whatsapp')?.get('parameters') as FormArray;
}
buildArrayParametersWhatsApp() {
return this._formBuilder.array([]);
}
addParameterWhatsApp() {
const parametersArray = this._formBuilder?.group({
posicao: [],
valor: [],
});
if (parametersArray) {
this.parameters.push(parametersArray);
}
}
Image:
What I am missing?

At least in the code you show us, you are not given value to "dataSource" variable, only have its declaration (it should be 'undefined').
That is probably what is causing it to throw errors.