Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clicked. The challenge is that it should delete all rows if the top checkbox is selected, which selects all rows. Additionally, it should be able to delete a single row when a specific row's checkbox is clicked. Below, I have provided the code snippet and a plunkr example from my application to give a clearer idea of row selection.

https://plnkr.co/edit/7l4AltdWfLGdLaXgF4vl?p=info

@Component({
      select
or: 'my-app',
      template: `
        <div>
          <h2>Hello Angular2</h2>
          <table class="table table-bordered table-condensed table-striped table-hover">
            <thead>
                <tr>
                    <th></th>
                    <th>Size</th>
                    <th>Diameter</th>
                    <th class="text-center">
                        <input type="checkbox" name="all" [checked]="isAllChecked()" (change)="checkAll($event)"/>
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr *ngFor="let size of sizes ; let i = index">
                    <td class="text-right">{{i + 1}}</td>
                    <td class="text-right">{{size.size}}</td>
                    <td>{{size.diameter}}</td>
                    <td class="text-center">
                        <input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state"/>
                    </td>
                </tr>
            </tbody>
          </table>
        </div>
      `,
    })
    export class App {
      sizes: any[] = [
        { 'size': '0', 'diameter': '16000 km' },
        { 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' },
{ 'size': '1', 'diameter': '32000 km' }
      ];

      checkAll(ev) {
        this.sizes.forEach(x => x.state = ev.target.checked)
      }

      isAllChecked() {
        return this.sizes.every(_ => _.state);
      }
    }

    @NgModule({
      imports: [ BrowserModule, FormsModule ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}

Answer №1

Could you please verify the content in this link

verifyContent(size) {
    size.status = !size.status;
}
  
removeContent() {
    this.contents.forEach(x => {
      if(x.status) { alert(x.content); }
    });
}
<td class="text-center">
  <input type="checkbox" name="contentcb[]" value="{{content.id}}"
  [(ngModel)]="content.state" (click)="verifyContent(content)"/>
</td>
...
<button (click)="deleteContent()">Delete</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

Trying out cellRenderer in Angular's Ag Grid with Jest to validate values

I am facing an issue where I need to test the actual values displayed in a column of an Ag Grid table. These values are formatted using a cellRenderer based on specific conditions. In my Jest test, I have experimented with various approaches: Using fixtu ...

Having issues with Angular Material's mat-icon rendering weird symbols?

I'm facing an issue with an Angular material button that some users are also experiencing. In the Chrome browser, the icons are displaying incorrectly. Instead of the expected icons, strange characters are showing up. For example, the menu icon is sho ...

Creating a jQuery AJAX form that allows users to upload an image, submit the form, and store the entered values in a MySQL database

I am struggling with an HTML form that I am trying to submit using jQuery's $.ajax(); The form needs to: 1. Upload an image to a directory with error checks 2. Save the image path to a MySQL database 3. Insert two other form values (input and select) ...

What changes can be made to this function in order for the arches to be positioned directly in front of the camera?

I devised a method that arranges arches in front of a camera, side by side: <!-- HTML --> <a-curvedimage v-for="(value, index) in model" :theta-length="42" :rotation="setThumbsRotation(value, index)"> </a-curvedimage> <a-camera ...

Troubleshooting AngularJS2 and npm in WebStorm and Chrome for Windows users

Having completed the official Hero tutorial for AngularJs2 using Visual Studio Code, I decided to switch my coding and debugging setup to WebStorm+Chrome on Windows 10. To achieve this transition, I took the following steps: Installed Chrome JetBrains ...

Eslint has encountered a parsing error, it was not expecting that token

I encountered the issue Error: Unexpected token .. raised by eslint while working with this code snippet. Can anyone spot what's causing it? const Public = ({ loggingIn, authenticated, component, ...rest }) => ( <Route {...rest} render={(pr ...

JQuery Accordion SubMenu/Nested Feature malfunctioning

I have successfully implemented a JQuery Accordion on my website and it is functioning properly, opening and closing as expected. However, I am facing an issue when trying to add a submenu within the accordion. The submenu does not work as intended and lac ...

Convert the object containing arrays to a boolean value, which will be true if at least one of the arrays is not empty

Here's the scenario: searchCriteria: { filter1: [?], filter2: [?], filter3: [?], and so on } I am aiming for a boolean output that indicates whether any of the filter arrays contain data (i.e. are not empty). Something along the lines of: co ...

Steps for preventing text manipulation in ng2-ace-editorWould you like to restrict users from copying, pasting

How can I prevent users from copying, pasting, and dropping text in ng2-ace-editor? https://github.com/fxmontigny/ng2-ace-editor is the library I implemented in my Angular 5 application. ...

Selecting random numbers in React.js

I am working on creating a Netflix Clone and I want to change the banner image every time the page refreshes. I have integrated movie details from TMDb and have an array containing these details. My goal is to select a random number between 0 and 19 and us ...

The callback function is not responding properly in my HTTP POST request

I'm currently working with some code that involves callbacks: function getUserToken(data, callback) { var password_sha256 = sha256(data.password); getAppById(data.app_id).then(function(res) { console.log("app"+res); if (!r ...

The null object does not have a property addEvenListener and therefore cannot be

My goal is to develop a simple single-page application without using any frameworks, focusing on providing users with tutorials on specific subjects. I am encountering an issue with the javascript code for my page, receiving the following error: Uncaug ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

What is the best way to establish and maintain lasting connections with the Firebase database while utilizing the superagent

Currently, I am following the Firebase Functions documentation on enhancing Firebase database performance. I have provided the code snippet below for your reference. const request = require('superagent'); const functions = require('fireba ...

Add to and subsequently remove the possibility of deleting that element

I encountered an issue while moving elements from one div (x) to another div (y). The problem is that the elements in div x are deletable, but once they are copied to div y, they cannot be deleted. Here is the initial state: After deleting Filter 1, the ...

Ag-Grid is displaying a third column that is not present in my dataset

Recently, I've been working with Angular and incorporating the Ag-Grid into my project. My goal is to display a grid with two columns; however, upon implementation, an unexpected third separator appears as if there are three columns in total. Even w ...

I'm looking for assistance on how to set the minimum height using jQuery. Can anyone provide

My attempt to use the minHeight property in one of my divs is not successful, and I am unsure why... <div id="countries"> <div class="fixed"> <div class="country" style="marging-left:0px;"></div> <div class="country"&g ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Validating the body in Node.js for POST and PUT requests

When working in a production setting, what is considered the standard for POST / PUT body validation? I typically approach it like this: const isValid = (req.body.foo && /[a-z0-9]*/i.test(req.body.foo)) This method involves checking that the var ...

Angular2 (AngularCLI) cannot locate the Elasticsearch module

Currently, I am attempting to incorporate the Elasticsearch NPM Module into my Angular2 application. In order to use it in my service, I have imported it as follows: import { Client, SearchResponse } from 'elasticsearch'; Even though there are ...