Strategies for Extracting td Values and Manipulating Arrays in Angular 8

I am having trouble trying to capture the product name of a checked checkbox's row and add it to an array. Additionally, I want to remove the product name from the array if the checkbox is unchecked. I attempted a solution but it is not functioning as expected. Any help would be greatly appreciated.

For a live demonstration, you can visit: https://stackblitz.com/edit/angular-b6urvc?file=src/app/app.component.ts

The code in app.component.ts is provided below:

 getProduct(event){
    if(event.target.checked)
    {
        const target = e.originalEvent.toElement.closest('tr');
        let tdProduct = target.querySelector('td:nth-child(3)').innerText;
        productArr.push(tdProduct); 
    } else {
        const target = e.originalEvent.toElement.closest('tr');
        let tdProductRemove = target.querySelector('td:nth-child(3)').innerText;
        productArr.pop(tdProductRemove);  
    }
    console.log(productArr); 
}

Answer №1

Instead of performing complex operations to identify the product based on the DOM, simply pass the product in the event handler.

component.ts

getProduct(e, product){

 if(e.target.checked)
 {
    this.productArr.push(product.product_name); 
 }
 else
 {
    this.productArr.splice(this.productArr.indexOf(product.product_name), 1);  
 }

component.html

<td> <input type="checkbox" (change)="getProduct($event, data)"> 

View Stackblitz demo

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

Code shared among several angular4 modules

Within my company, we are facing a challenge where there are multiple angular4 modules within a single Intellij project that contain duplicated common code. This includes Angular components, assets such as images and fonts, and dependencies like bootstrap ...

Utilizing a single AWS IoT connection for every component in Angular 6: A complete guide

In my Angular 6 project, I integrated AWS IoT for chat and notification functionalities. Initially, I was connecting to AWS IoT from multiple components like the header, chat, and home components. However, I now want to streamline the process by establishi ...

Conceal the menu in Angular Material when the mouse leaves the button

When the mouse hovers over a button, a menu is displayed on the website's toolbar. The menu is set to close when the mouse leaves a surrounding span element. Now, there is an attempt to also close the menu when the mouse leaves the triggering button i ...

What is the best way to interpret and execute conditions specified within strings like "condition1 and condition2"?

Received a JSON file from an external source with various conditions that need to be tested, either in real-time or through conversion. Imagine having an instance of a class called Person, with attributes {age: 13, country: "Norway"}, and an ext ...

What are the benefits of combining Express and Firebase?

Embarking on my journey to learn the MEAN stack, I initially planned to use Firebase instead of Mongo.db and Angular2 instead of Angular. However, I encountered difficulties when attempting to set up Angular2 with Express in a straightforward manner. Durin ...

Tips on incorporating dynamic expressions within ngFor loops?

Is there a way to dynamically display specific properties from objects in an array (list: any[]) within an *ngFor loop in Angular? I am currently working on a component called ListComponent that is responsible for rendering a list of items. The parent com ...

Can dynamic attributes be used with ternary operators in Angular?

I attempted to alter the id of a div using Angular and implemented the following code: <div [id]="'item_' + (itemName !== undefined ? itemName.replace(' ', '-').toLowerCase() : '')"> However, when I run my te ...

Encountering an unexpected token while trying to use createUserWithEmailAndPassword in firebase/auth with Next.js and TypeScript left Jest puzzled

I have been working on integrating Firebase authentication into my Next.js project (using TypeScript), but it appears that there are configuration issues with Firebase causing my Jest tests to fail. Here are the key configuration files: jest.config.js : ...

Why has Jasmine decided not to wait for my promises to finish?

Utilizing the FileSystem API to generate a directory with 2 entries for a test, I am facing an issue where Jasmine does not wait for the promise to resolve before executing the test, resulting in failure. Despite using the async wrapper, the problem persis ...

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

Combining files/namespaces/modules in Typescript: How to do it?

Even though I believe the solution may be simple, understanding how to merge enums across multiple files is eluding me when reading through the documentation. // a.ts enum Color{ RED, BLUE } // b.ts enum Day{ MONDAY, TUESDAY } // c ...

Unable to cache new entry at the specified location (/Users/android/.gradle/7.5.1/checksums/sha1-checksums.bin) due to a java.io.IOException with the message "Bad file descriptor"

I encountered two errors when trying to run my React Native project. Issue 1: Failed to add entry '/Users/saadafridi/.gradle/.tmp/gradle_download14928641310389655157bin' to cache sha1-checksums.bin (/Users/saadafridi/Desktop/mobileapp/android/.g ...

Steps to activate Angular Progressive Web App service worker

When I set up an Angular project, I executed the following commands in the terminal: ng add @angular/pwa ng build --prod The static website output was published in the /dist folder. After running the URL through PWABuilder, it detected the manifest bu ...

Incorporate SVG files into a TypeScript React application using Webpack

I am trying to incorporate an SVG image into a small React application built with TypeScript and bundled using Webpack. However, I am encountering an issue where the image is not displaying properly (only showing the browser's default image for when n ...

Why was the event handler attached and for what purpose does it serve in this particular location?

When using Typescript with JQuery, I encountered a strange issue where a click event seemed to be added multiple times each time the user opened a dialog. Despite creating a new SettingsDlog object for each dialog instance, the click event did not behave a ...

Using Angular, create mat-checkbox components that are dynamically generated and bound using

In my Offer class, I have a property called "units" which is an array of objects. export class Offer { public propertyA: string; public propertyB: string; public units: Unit[]; } export class Unit { public code: string, public name: ...

Emitting events from a parent component to a child component

In the scenario mentioned above, using (click)="toggleSideBar()" in side-bar.component.ts does not close the sidebar. Is there a solution to this issue? ...

Mastering checkbox selection in Angular reactive formsLearn how to effortlessly manage the checked status of

I am struggling with setting the checked status of a checkbox control within an Angular reactive form. My goal is to change the value based on the checked status, but it seems like the value is controlling the status instead. For instance, I want the for ...

Preventing the continuation of an Observable chain in RXJS based on a specific condition

Exploring a New Approach I am currently venturing into the realm of creating a route guard in Angular2+, utilizing Observables from a shared service that stores the current user's role as a string. The challenge lies in transitioning my thought pro ...

Installing and running Node.js within a tomcat server

After creating a web application using Angular, Node/Express, and MySQL, I faced an issue with deployment. My Angular app is running on a tomcat server connected to multiple PCs, but now I need to also deploy my backend (Node.js/Express.js) on the same s ...