【发布时间】:2021-08-09 16:12:21
【问题描述】:
我不能在我的角垫表中使用*ngFor,或者我只是没有这方面的知识。如果有人可以帮助我,我将不胜感激?
我想删除数组中的一行,例如使用一个按钮,然后将其列在我的表上,但它不起作用。因此我想使用*ngFor 来显示表格数据,但是如果我点击ADD 按钮,它会添加另一行,里面没有数据。
这是我目前得到的:
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);
}
}
我做了一个 StackBlitz,但遗憾的是它不起作用我无法让它工作来导入模块,我尝试了很长时间。 https://stackblitz.com/edit/add-angular-material-o2pu6c?file=src%2Fmain.ts
谢谢!
【问题讨论】:
标签: angular typescript angular-material mat-table