Is it possible to remove a complete row in Angular 2 using Material Design

JSON

[
  { position: 1, name: 'test', value: 1.0079, symbol: 'HHH' },
  { position: 2, name: 'test2', value: 4.0026, symbol: 'BBB' },
  { position: 3, name: 'test3', value: 6.941, symbol: 'BB' },
  { position: 4, name: 'test4', value: 9.0122, symbol: 'CC' },
]

TS

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  removeSelectedRows() {
     this.selection.selected.forEach(item => {
      let index: number = this.data.findIndex(d => d === item);
      console.log(this.data.findIndex(d => d === item));
      this.dataSource.data.splice(index,1);

      this.dataSource = new MatTableDataSource<Element>(this.dataSource.data);
      setTimeout(() => {
        this.dataSource.paginator = this.paginator;
      });
    });
    this.selection = new SelectionModel<Element>(true, []);
  }

  /** 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));
  }
}

HTML

<div class="example-container mat-elevation-z8">

  <mat-table #table [dataSource]="dataSource">

    <!-- Checkbox Column -->
    <ng-container matColumnDef="actions">
      <mat-header-cell *matHeaderCellDef>
      </mat-header-cell>
      <mat-cell *matCellDef="let row">
        <button mat-icon-button color="#b71c1c">
                    <mat-icon aria-label="Delete">delete</mat-icon>
                  </button>
      </mat-cell>
    </ng-container>

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

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

    <!-- Symbol Column -->
    <ng-container matColumnDef="symbol">
      <mat-header-cell *matHeaderCellDef> Symbol </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.symbol}} </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>
  </table>


</div>

i want to delete the entire row using one click button Explanation -> when i click on delete button the entire row should get delete but here I'm doing API call for example when i delete any row it will send name to the API!

here it is my stackbliz demo -https://stackblitz.com/edit/delete-rows-mat-table-f5f7tr?file=app%2Ftable-selection-example.ts

Answer №1

If you want to remove a row in Angular, you can use the following code snippets:

Here is the HTML code:

<!-- Checkbox Column -->
<ng-container matColumnDef="actions">
  <mat-header-cell *matHeaderCellDef> </mat-header-cell>
  <mat-cell *matCellDef="let row">
    <button mat-icon-button color="#b71c1c" (click)="removeSelectedRow(row)">
      <mat-icon aria-label="Delete">delete</mat-icon>
    </button>
  </mat-cell>
</ng-container>

And here is the TypeScript code:

removeSelectedRow(row) {
    //const index = this.data.findIndex(obj => obj === row);
    const index = this.data.findIndex(obj => obj.codeData == row.codeData);
    this.data.splice(index, 1);
    this.dataSource = new MatTableDataSource<Element>(this.dataSource.data);
}

You can try the code in action on StackBlitz by clicking here

After implementing this, you should see the result as shown in this animation

Answer №2

It's advisable to verify if index != -1 before proceeding.

deleteSelectedRows(row) {
    let index = DATA_LIST.findIndex(x => x.position == row.position);

    if (index != -1) {
      DATA_LIST.splice(index, 1)
    }
    this.updatedSource = new MatTableDataSource<Data>(DATA_LIST);
}

Answer №3

Include a method to remove the specified row:

  removeRow(row) {
    this.dataList.splice(row.position-1, 1);
    this.dataList = new MatTableDataSource<Element>(this.dataList);
  }

Then, in the HTML file, trigger this method when the delete button is clicked

<button (click)="removeRow(row)" mat-icon-button color="#b71c1c">
      <mat-icon aria-label="Delete">delete</mat-icon>
</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the role of the handleSubmit parameter in React Hook Form?

I'm encountering an issue with TypeScript in the handleSubmit function. To start off, I am accessing the handleSubmit function through the useForm hook: const {handleSubmit, control, watch, reset} = useForm() Next, I define a submit function: con ...

Angular Update Component on Input ChangeEnsuring that the component is automatically

<div class=" card-body"> <div class="row"> <div class=" font-icon-list col-lg-2 col-md-3 col-sm-4 col-xs-6 col-xs-6" routerLinkActive="active" *ngFor="let subject of subjects"> <div class=" fon ...

sticky header on pinned tables in a React data grid

I have combined 3 tables together, with the middle table containing a minimum of 15 columns. This setup allows users to horizontally scroll through the additional columns conveniently. However, I am facing a challenge in implementing a sticky header featu ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Handling ngRouterOutlet and component lifecycle - difficulties with displaying personalized templates

Overview I have developed a custom table component using Angular Material to display data and columns based on user configurations. While the component includes default templates for basic data types like strings and numbers, users are able to create thei ...

Travis build unsuccessful due to version inconsistencies

I am facing an issue where my locally working application is failing to build on TravisCI. After some research, I realized that I used "latest" as the version for dependencies in my package.json file. :rekolekcje-webapp:npmInstallnpm WARN deprecated <a ...

How to exit a dialog in an Angular TypeScript component with precision

Hey there, I'm attempting to close a dialog from the component by specifying the path in .angular-cli.json and calling the function. However, it seems that despite my efforts, the dialog isn't closing and the redirection isn't happening. He ...

I am experiencing a 404 error when attempting to import a local JS file in Angular

After creating a new project with "ng new xxx", all you need to do is add one line of code in index.html: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Bbb</title> <base href="/&g ...

Updating an element within a for loop using Angular TypeScript

I'm trying to figure out how to update the value of an HTML DOM element that is bound from a TypeScript file in each iteration of a for loop, rather than at the end of the loop. I want to see all values as the loop is running. For example, imagine I ...

Issues with CSS Styling not being applied properly on mobile devices in a React App deployed on Heroku

The Dilemma My React app is deployed on Heroku using create-react-app for bundling. The backend is a Node.js written in Typescript with node version 10.15.3. Locally, when I run the site using npm start, everything works perfectly. However, when I view t ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Exploring Angular unit testing for immutable variables

Currently, I am working on writing unit tests for a specific class that contains readonly class variables. I am trying to ensure complete test coverage and understand how to cover the logic inside these variables. import { Injectable } from '@angu ...

Following the execution of the "ng build --prod" command in Angular 2, the functionality of ui

Utilizing an Angular program with a Node.js server and the ng serve command has been successful. However, when attempting to transfer this code to a shared Linux server and using XAMPP for compilation, an error was encountered: ng build --prod The error ...

The type 'string' cannot be assigned to the type 'T[keyof T]' within this context

I have a function that processes an array of Episodes and assigns data from an external file to the corresponding Episode based on a specified keyName: const assignDataFromExternalFile = (arrayToProcess: Episode[], filePath: string, keyName: keyof Episode) ...

Angular 4 is having trouble retrieving the JSON response

When I attempt to log errors in a specific scenario and use error, the following error message is displayed: { "errors" : [ { "entity" : "Movement", "property" : "direction", "invalidValue" : null, "message" : "Il campo non può essere v ...

Unleashing the power of Angular 7+: Extracting data from a JSON array

As a newcomer to Angular and API integration, I am facing a challenge in fetching currency exchange rates data from the NBP Web API. The JSON file structure that I'm working with looks like: https://i.stack.imgur.com/kO0Cr.png After successfully ret ...

Mixing Jest and Cypress in a TypeScript environment can lead to Assertion and JestMatchers issues

When utilizing [email protected] alongside Jest, we are encountering TypeScript errors related to Assertion and JestMatchers. What is the reason for these TypeScript errors when using Jest and [email protected] in the same project? ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

Developing the headers for a service using React.js

As someone new to ReactJs, I'm curious about the various methods we can use to include Headers in our service Url before making a call. While I'm familiar with how GET/POST Calls are made in angular Js after including headers, I'd like to l ...