如何从垫台材料设计表中删除垫行

时间:2018-10-08 04:50:40

标签: angular angular-material

我正在使用Angular Material的表格组件来显示来自API的数据。如何从表行中删除数据记录?

HTML模板:

.finally

<div> <mat-table [dataSource]="dataSource" #table> <ng-container matColumnDef="userId"> <mat-header-cell *matHeaderCellDef> Name </mat-header-cell> <mat-cell *matCellDef="let user"> {{user.userId}} </mat-cell> </ng-container> <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef> E-Mail </mat-header-cell> <mat-cell *matCellDef="let user"> {{user.id}} </mat-cell> </ng-container> <ng-container matColumnDef="title"> <mat-header-cell *matHeaderCellDef> Phone </mat-header-cell> <mat-cell *matCellDef="let user"> {{user.title}} </mat-cell> </ng-container> <ng-container matColumnDef="body"> <mat-header-cell *matHeaderCellDef> Company </mat-header-cell> <mat-cell *matCellDef="let user"> {{user.body}} </mat-cell> </ng-container> <ng-container matColumnDef="remove"> <mat-header-cell *matHeaderCellDef> <button mat-icon-button (click)="removeAll()" matTooltip="Remove all"> <mat-icon>clear_all</mat-icon> </button> </mat-header-cell> <mat-cell *matCellDef="let user; let i = index;"> <button mat-icon-button (click)="removeAt(i)" matTooltip="Remove this score"> <mat-icon>clear</mat-icon> </button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table> </div>

user.component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; import { from } from 'rxjs/internal/observable/from'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { DataSource } from '@angular/cdk/collections'; import { SummaryService } from './summary.service'; import { User } from './user'; @Component({ selector: 'app-summary', templateUrl: './summary.component.html', styleUrls: ['./summary.component.scss'] }) export class SummaryComponent implements OnInit { dataSource = new UserDataSource(this.summaryService); displayedColumns = ['userId', 'id', 'title', 'body', 'remove']; usersList: Observable<User[]>; constructor(private summaryService: SummaryService) { } ngOnInit() { } } export class UserDataSource extends DataSource<any> { constructor(private userService: SummaryService) { super(); } connect(): Observable<User[]> { return this.userService.getUsers(); } disconnect() { } }

summary.service.ts

1 个答案:

答案 0 :(得分:0)

由于表是从dataSource数组生成的,因此可以使用splice函数删除所选索引上数据源的and元素。例如,您可以根据user.component.ts文件中的逻辑,在removeAt函数中执行以下操作:

removeAt(i){    
    this.dataSource.splice(i,1);
    this.dataSource=JSON.parse(JSON.stringify(this.dataSource));// this line is to refresh view and detect changes for updating table view

}