angularselectionmodel

ERROR TypeError: this.dataSource.findIndex is not a function


I have this:

    removeSelectedRows() {

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

I want to delete the selected rows and I found this code on the internet, but it gives me an error:

RefactorComponent.html:12 ERROR TypeError: this.dataSource.findIndex is not a function
    at refactor.component.ts:65
    at Array.forEach (<anonymous>)
    at RefactorComponent.removeSelectedRows (refactor.component.ts:64)
    at Object.eval [as handleEvent] (RefactorComponent.html:12)
    at handleEvent (core.js:43993)
    at callWithDebugContext (core.js:45632)
    at Object.debugHandleEvent [as handleEvent] (core.js:45247)
    at dispatchEvent (core.js:29804)
    at core.js:42925
    at HTMLButtonElement.<anonymous> (platform-browser.js:2668)

I need you to take the position of that row that is selected, to delete it from the dataSource. I'm using angular 8.


Solution

  • if your datasource defined like this

    this.dataSource = new MatTableDataSource<Element>(dataArray);
    

    you need to call method findIndex on this.dataSource.data like this

    this.dataSource.data.findIndex(d => d === item);