Having trouble implementing *ngFor in my angular mat table, seeking guidance from someone with more expertise?
I am trying to delete a row within an array using a button and display it on my table, but encountering issues. I intend to utilize *ngFor to showcase the table data, however, clicking the ADD button simply adds another empty row.
https://i.stack.imgur.com/KQd45.jpg
This is the current code snippet:
angular-table.component.html
<table mat-table *ngFor="let item of data" class="mat-elevation-z8" matSort>
<ng-container matColumnDef="title">
<th mat-header-cell *matHeaderCellDef>Title</th>
<td mat-cell *matCellDef> {{item.title}} </td>
</ng-container>
<ng-container matColumnDef="id" id="id">
<th mat-header-cell *matHeaderCellDef>ID</th>
<td mat-cell *matCellDef> {{item.id}}</td>
</ng-container>
<ng-container matColumnDef="delete">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Test</th>
<td mat-cell *matCellDef>
<mat-icon (click)="removeCart(i)" class="removeCart">close</mat-icon>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<button (click)="ADD1()">Add1</button>
<button (click)="ADD2()">Add2</button>
angular-table.component.ts
export class AngularTableComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
amount: number;
data: any = [];
id: number = 2;
title: string = 'test';
displayedColumns: string[] = ['title', 'id', 'delete'];
ADD1(){
const id = this.id;
const title = this.title;
const newData = {
id,
title
}
this.data.push(newData);
console.log(this.data);
}
ADD2(){
const id = this.id = 7;
const title = this.title = "Hello";
const newData = {
id,
title
}
this.data.push(newData);
console.log(this.data);
}
removeCart(index: number){
this.data.splice(index, 1);
}
}
I tried creating a StackBlitz, but faced challenges importing the modules. Here is the link: https://stackblitz.com/edit/add-angular-material-o2pu6c?file=src%2Fmain.ts
Appreciate any assistance!