Guidelines for eliminating a row from an Angular Material table

I am currently working on a shopping cart feature using an Angular Material table. Each row in the table displays a picture, description, and a delete button. However, I'm facing an issue where clicking the delete button does not remove the row from the table until all items are deleted. Although the item is successfully removed from the cart, it doesn't reflect in the table unless I refresh or re-initialize the component. I tried adding a div with an *ngFor loop at the end, which correctly displays the number of items when a delete action is performed, but the table still fails to update accordingly. My setup includes a cart.model.ts file, a cart.service.ts for handling actions like deletion, and the cart component itself. While I could resort to CSS modifications or libraries, I'd prefer to address this "problem" directly. Any assistance on resolving this issue would be greatly appreciated. Thank you in advance! https://i.sstatic.net/LcXdv.png

cart.component.html

    <div class="mat-display-3" style="background-color: #d6d6d6;
              padding: 20px;
              color: #a7181b;
              text-align: center;" *ngIf="cart.length === 0">
        Your cart is Empty!
    </div>
    <table mat-table [dataSource]="cart" class="mat-elevation-z8" *ngIf="cart.length > 0">
        <ng-container matColumnDef="product">
            <th mat-header-cell *matHeaderCellDef> Product </th>
            <td mat-cell *matCellDef="let cartItem"> <img src="{{ cartItem.image }}" alt="{{ cartItem.name }}"> </td>
        </ng-container>
        <ng-container matColumnDef="description">
            <th mat-header-cell *matHeaderCellDef> Description </th>
            <td mat-cell *matCellDef="let cartItem">
                <p>Name: {{ cartItem.name }}</p>
                <p>Type: {{ cartItem.type }}</p>
                <p>Size: {{ cartItem.size }}</p>
            </td>
        </ng-container>
        <ng-container matColumnDef="quantity">
            <th mat-header-cell *matHeaderCellDef> Quantity </th>
            <td mat-cell *matCellDef="let cartItem"> <input type="number" min="1" max="10" value="{{ cartItem.quantity }}" [disabled]="cartItem.type==='original'"> </td>
        </ng-container>
        <ng-container matColumnDef="price">
            <th mat-header-cell *matHeaderCellDef> Price </th>
            <td mat-cell *matCellDef="let cartItem">
                <h2>${{ cartItem.price }}.00</h2>
            </td>
        </ng-container>
        <ng-container matColumnDef="delete">
            <th mat-header-cell *matHeaderCellDef> Delete </th>
            <td mat-cell *matCellDef="let cartItem"> <button mat-fab color="warn" (click)=onDeleteProduct(cartItem.inCartProductId)><mat-icon>delete</mat-icon></button> </td>
        </ng-container>
    
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
    <div *ngFor="let x of cart">
        <p>{{ x.name }}</p>
    </div>

cart.service.ts

  private cart: CartItem[] = [
  ]

  addToCart(name: string, type: string, image: string, size: string, quantity: number, price: number){
    let inCartProductId = this.cart.length > 0 ? this.cart[this.cart.length-1].inCartProductId+1 : 1;
    this.cart.push({inCartProductId: inCartProductId, name: name, type: type, image: image, size: size, quantity: quantity, price: price});
  }

  getCart(){
    return this.cart;
  }

  deleteFromCart(inCartProductId: number){
    const product = this.cart.find(p => {
      return p.inCartProductId === inCartProductId;
    });
    if(product){
      this.cart.splice(this.cart.map(p => p.inCartProductId).indexOf(inCartProductId), 1);
    }
  }
}

cart-item.model.ts

export class CartItem {
  constructor(
    public inCartProductId: number,
    public name: string,
    public type: string,
    public image: string,
    public size: string,
    public quantity: number,
    public price: number
  ){}
}

Answer №1

When modifying the datasource (cart), the mat-table may fail to render the changes. To ensure it updates properly, you must manually trigger a re-render. In your TypeScript file (.ts):

@ViewChild(MatTable, {static: false}) table: MatTable<CartItem>;

Whenever you make changes to the cart by adding or deleting items, include this line of code:

this.table.renderRows();

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

The error message "SharedArrayBuffer is not defined" occurred when attempting to utilize ffmpeg.wasm

<!DOCTYPE html> <html> <head> <title>TikTok Live Downloader</title> </head> <body> <h1>TikTok Live Downloader</h1> <label for="username">Username:</label> ...

Search for Div IDs while filtering as you type

Is there a search jQuery plugin that enables real-time filtering based on Div ID as you type in the search box? It would be great if the filter instantly refreshes. ...

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

Is there a way to navigate to a specific <li> element using scrolling?

Is there a way to direct a user to a URL and have it automatically scroll to a specific <li> element? For example, navigating to mysite.com/something.html#someItem should take the user directly to: Something here ...

Issue arising from passing an object through a component in a Next.js application during build time when the object is retrieved from a database

Can anyone provide assistance with solving this issue? I have an object called "diary" coming from a database, which is passed to a component where a useState hook is expecting that object. During build time, the following error is occurring. An error is ...

Encountering a snag when attempting to access a property following the invocation of a REST service in Angular

I recently started learning Angular and I am currently working on a practice application. My goal is to call a rest service and retrieve a specific property from the response object in Angular, but unfortunately, I encountered an error. Below you can find ...

Encountered a problem when attempting to access an element on a PHP page using

My javascript code is supposed to retrieve information from a specific URL (song.php) which contains the name of a song. However, there seems to be an issue as the javascript is not extracting the required data. Below is the HTML element and javascript fo ...

Tips for converting string values from an Observable to numbers using the parseFloat() method

Having trouble converting text to numbers for geolocation coordinates. My model consists of a site with an ID and an array of points as a property. Rather than creating a relationship between site and points, I've structured it differently. In my cod ...

What is the best way to pass parameters to a PHP script using AJAX to ensure they are properly processed on the server side?

I'm working with the following function: function myFunction () { $.getJSON('remote.php', function(json) { var messages = json; function check() { ... In this function, I call the remote.php script which e ...

I am encountering an issue with the Node library puppeteer when trying to integrate it with vue.js

While following a YouTube tutorial on utilizing puppeteer in JavaScript, I encountered an issue where the page would not render even if I required the library. The problem seemed to be located right below where I imported my Vue components: <script> ...

A JavaScript AddEventListener will not execute a function that has parameters

Attempting to execute a function with two parameters in NuxtJS upon clicking an element using AddEventListener. async handleSubmit(recipe, userRating) {some code...} setup(recipe) { document.querySelectorAll('.recipe-rating > .star').forEac ...

ordering the date and time in a reverse sequence using javascript

I am working with dynamically generated date and time data and I am looking to sort them in descending order using JavaScript. Here is an example of the data format I am dealing with: var array= ["25-Jul-2017 12:46:39 pm","25-Jul-2017 12:52:23 pm","25-Ju ...

Waiting for a page to fully load using Selenium and JavaScript

After clicking a link, I have to wait for the webpage to finish loading. The title of the new page remains unchanged, but the URL changes from "something.com" to "something.com/abc". Because of this, I am unable to utilize driver.wait(until.titleIs(&apo ...

Having trouble retrieving accurate text information from a JavaScript link

I am encountering an issue with my code which consists of links with divs inside them. When I click on a link, it should display another div with data for "Case No" and "Type". However, the problem is that it only fetches the data from the first link click ...

How to specify a single kind of JavaScript object using Typescript

Let's say we have an object structured as follows: const obj = [ { createdAt: "2022-10-25T08:06:29.392Z", updatedAt: "2022-10-25T08:06:29.392Z"}, { createdAt: "2022-10-25T08:06:29.392Z", animal: "cat"} ] We ...

Update the text in the textarea using jQuery or JavaScript

I have incorporated gridster widgets into my webpage, each with multiple images and a textarea. The textarea contains links to the images separated by commas, initially populated from JSON. Users can delete images from the grid, and I want the textarea con ...

Developing a collection of customized shapes comprised of circular-edged rectangles using the Three.JS

I have been on a quest for some time now. My aim is to replicate this visual element from - the beautifully arranged deck of cards. I know it was created using Three.JS, and my goal is to recreate it exactly as seen in that link. The challenge I'm c ...

Despite declaring a default export, the code does not include one

Software decays over time. After making a small modification to a GitHub project that was three years old, the rebuild failed due to automatic security patches. I managed to fix everything except for an issue with a default import. The specific error mess ...

Creating a Turn.js interactive book similar to the provided example?

I'm in the process of creating a book using turn.js with Jquery and everything is going smoothly so far. However, I could use some assistance. I am trying to achieve the look of a hard-backed journal-type book similar to the example provided here . My ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...