使用角度材质表从角度2中删除表中的选定行

时间:2018-01-20 08:33:53

标签: angular angular-material2

我正在尝试使用角度材质选择表在角度2中实现一个简单的表格。

我用一个按钮从表中删除选定的行。但是点击按钮我该如何删除行?

下面显示的是我的表

的html文件
<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">

    <!-- Checkbox Column -->
    <ng-container matColumnDef="select">
      <mat-header-cell  style="max-width: 100px;" *matHeaderCellDef>
        <mat-checkbox (change)="$event ? masterToggle() : null"
                      [checked]="selection.hasValue() && isAllSelected()"
                      [indeterminate]="selection.hasValue() && !isAllSelected()">
        </mat-checkbox>
      </mat-header-cell>
      <mat-cell   style="max-width: 100px;" *matCellDef="let row">
        <mat-checkbox (click)="$event.stopPropagation()"
                      (change)="$event ? selection.toggle(row) : null"
                      [checked]="selection.isSelected(row)">
        </mat-checkbox>
      </mat-cell>
    </ng-container>

    <!-- Number Column -->
    <ng-container matColumnDef="num">
      <mat-header-cell style="max-width: 100px;" *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell style="max-width: 100px;" *matCellDef="let element"> {{element.num}} </mat-cell>
    </ng-container>

    <!-- Message Column -->
    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef> Message </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
    </ng-container>


    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"
             (click)="selection.toggle(row)">
    </mat-row>
  </mat-table>

   <mat-paginator #paginator
                 [pageSize]="10"
                 [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</div>

<br/>
<button style="background: #3B4990; color:white;" (click)="deleted($event)">Remove Selected Messages</button>

下面显示的是我的.ts文件。

import {Component, ViewChild} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';
import {SelectionModel} from '@angular/cdk/collections';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
   styleUrls: ['./home.component.scss']
})


export class HomeComponent {

displayedColumns = ['select', 'num', 'name'];
  dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);



  @ViewChild(MatPaginator) paginator: MatPaginator;

  /**
   * Set the paginator after the view init since this component will
   * be able to query its view for the initialized paginator.
   */
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
  }

  selection = new SelectionModel<Element>(true, []);

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

    deleted($event)
{ 
 delete(this.dataSource.data.forEach(row => this.selection.select(row));)
}

}

export interface Element {
  name: string;
  num: number;
}

const ELEMENT_DATA: Element[] = [
  {num: 1, name: 'Message1'},
  {num: 2, name: 'Message2'},
  {num: 3, name: 'Message3'},
  {num: 3, name: 'Message4'},
  {num: 4, name: 'Message5'},
  {num: 5, name: 'Message6'},
];

任何人都可以帮助我如何使用按钮从表中删除选定的行。

4 个答案:

答案 0 :(得分:10)

您应该删除所选项目并刷新datasource,如下所示

removeSelectedRows() {
    this.selection.selected.forEach(item => {
       let index: number = this.data.findIndex(d => d === item);
       console.log(this.data.findIndex(d => d === item));
       this.data.splice(index,1)
       this.dataSource = new MatTableDataSource<Element>(this.data);
     });
     this.selection = new SelectionModel<Element>(true, []);
  }

<强> LIVE DEMO

答案 1 :(得分:2)

您可以使用MatTable API中的renderRows()方法。

这样,您无需在每次点击时重新实例化数组。

Check-out the Live Demo

答案 2 :(得分:1)

你可以试试下面吗?

  removeSelectedRows() {
    var oldData = this.dataSource.data;
    var oldData = oldData.filter((item) => !this.selection.selected.includes(item));
    this.dataSource = new MatTableDataSource<Topic>(oldData);
    this.selection.clear()
    this.dataSource.filter = "";
  }

答案 3 :(得分:0)

感谢Aravind的回答,帮助我解决了同样的问题。但是,我不喜欢MatTableDataSouce位于forEach循环中,因为我认为这意味着它正在每个循环上创建一个新的数据源。另外,对我而言,创建新的MatTableDataSource会破坏我对默认Paginator的使用。因此,我修改了他的答案,并在这里张贴给可能会受益的任何人。

removeSelectedRows() {   
    //sort the selected rows first so that they are in descending order
    //this allows us to splice without the index getting confused
    let selectedRows = this.selection.selected.sort((a,b) => {return b.position - a.position});

    let ds = this.dataSource.data; //take a copy

    selectedRows.forEach(item => {
        ds.splice(item.position-1,1); //splice out the selected rows
    });
    this.dataSource.data = ds;  //set the datasource so it fires the refresh

    this.selection = new SelectionModel<Element>(true, []);
}

还没有测试过,但是我猜想,接受的答案和我的答案都需要进行一些清理,因为位置将不同步,这可能意味着随后的呼叫失败。