Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these checkboxes and only delete those specific ones. In the delete function, I need to splice out the rows corresponding to the selected checkboxes from the main array.

Below is the HTML code snippet:


     <ng-container *ngFor="let reasoncode of displayReasonCodes$ | async; let i = index">
    <tr class= "row-break">
    <checkbox type="checkbox"  name="sizecb[]" value="{{reasoncode.id}}"  [(ngModel)]="reasoncode.state">
      </checkbox>
      <td>  
      <form>
    <form-group>
    <textbox [readOnly]="isEditable" ngModel="{{reasoncode.ReasonCode}}"  name="textbox" ></textbox>
    </form-group>
    </form>
    </td>
    <td>
    <form>
     <form-group>
    <textbox  [readOnly]="isEditable" ngModel="{{reasoncode.Description}}" name="textbox1" ></atextbox>
    </form-group>
    </form>
    </td>
    <form>
    <p>
    <toggle-switch   ngModel="{{reasoncode.Status}}"   name="switch1"  ></toggle-switch>
    </p>
    </form>
    </tr>
    </ng-container>
    </tbody>
    </table>

Here is the component.ts file:


export class ReasonCodesComponent implements OnInit {


    checkAll(event: any) {
      if (!this.result) return;
      this.result.forEach((x: any) => x.state = event.target.checked)
      }

     isAllChecked() {
      if (this.arr) return;
      return this.result.every((_: any) => _.state);
      }
     check(result: any) {
     result.state == false;
      result.state! = result.state;
      }
    @select(store.displayReasonCodes) displayReasonCodes$: Observable<IReasonCodes>;

      arr: any[];
      state: any;
      $event: any;
      displayReasonCodes: any;
      x: any;
      _: any;
      result: any;
      isEditable: boolean;

     constructor(private reasonCodesActions: ReasonCodesActions) {
      }

      reasoncodeObject:Object;
      ngOnInit() {

    this.displayReasonCodes$.subscribe(data => this.result = data ) 
      }

    deleterow() { 
        this.result.forEach((x: any) => {
          if (x.state) {  alert(x.state)  /// here i am getting true as alert for number of rows selected and when i clcik on delete.

            let copyObj = this.displayReasonCodes$.subscribe(data1=>this.data=(JSON.parse(JSON.stringify(data1))));

            console.log(this.data)  ; //data contains the array of objects, from which i have to splice up the number of selected rows from table.

          };
        })
      }

    }

The goal is to remove the selected rows in the checkbox and display the remaining ones.

Answer №1

If you change your field state from 'boolean' to 'any', consider implementing this approach: Exclude checked objects and only return the unchecked ones:

this.result = this.result.filter(el => {
    el.state == undefined || el.state == null || el.state == false;
});

Replace your forEach()-loop in the deleterow()-method with the provided code snippet.

Answer №2

Ah, now it all makes sense. I took your code from Plunkr and made some modifications to demonstrate how it functions:

Firstly, in your template I made a small change

<input type="checkbox" name="sizecb[]" value="{{size.id}}" [(ngModel)]="size.state" />

I updated it to include a (change) event listener:

<input type="checkbox" name="sizecb[]" (change)="checkOccurred()" value="{{size.id}}" [(ngModel)]="size.state" />

Then, I expanded the sizes-object to provide more options for output:

sizes: any[] = [
    { 'size': '0', 'diameter': '16000 km', 'state': false },
    { 'size': '1', 'diameter': '32000 km', 'state': false },
    { 'size': '23', 'diameter': '3000 km', 'state': false },
    { 'size': '22', 'diameter': '700 km', 'state': false },
    { 'size': '99', 'diameter': '377000 km', 'state': false }
];

Note that I added the 'state' field, which simplifies actions later on.

Additionally, I implemented two new methods:

private checkOccurred(): void {
    this.getSelectedCheckboxes();
}

private getSelectedCheckboxes(): any[] {
    const result: number[] = [];

    this.sizes.forEach((item, index) => {

        if (item.state === true) {
            result.push(index);
        }
    });

    console.log(result);

    return result;
}

The getSelectedCheckboxes() method provides a list of selected checkboxes indexes in your 'sizes' array, as requested.

I hope this explanation clarifies things for you.

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

Typescript Declarations for OpenLayers version 6

The package @types/openlayers found at https://www.npmjs.com/package/@types/openlayers only provides type definitions for version 4.6 of OpenLayers. This is clearly stated in the top comment within the file index.d.ts. If types for OpenLayers 6 are not av ...

The Angular web application utilizing an ASP.NET Web API that is hosted on AppHarbor is showing the incorrect webpage

Working on a web application using Angular and ASP.NET Web API in Visual Studio 2015 has been quite the journey for me. Upon running the solution in VS2015, I encountered two tabs opening in Chrome - one for my Angular client-side application and another ...

Incorporating lodash in a project with TypeScript and jspm

I seem to be missing something in my setup and would appreciate any assistance. I am working with TypeScript 2 + JSPM. I have tried various configurations in tsconfig using typeRoots and types (including adding the version number in the type name). Despite ...

Preventing duplicate requests when subscribing to an rxjs Observer multiple times

Currently, I am in the process of implementing a custom XHRBackend for my Angular 2 application. Here is the code snippet of the class: import {Request, XHRBackend, BrowserXhr, ResponseOptions, XSRFStrategy} from "@angular/http"; import "rxjs/add/operator ...

VueJS with Vuetify: Issue with draggable cards in a responsive grid

I am currently working on creating a gallery that allows users to rearrange images. To test this functionality, I am using an array of numbers. It is important that the gallery is responsive and displays as a single column on mobile devices. The issue I ...

Why do optional values of objects remain optional when being checked in an if statement in Typescript?

Recently at work, I encountered this code snippet and was left wondering why Typescript couldn't comprehend the logic behind it. If 'test' in the object can either be undefined or a string, shouldn't it logically infer that within an if ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Revitalizing HTML and Google Maps with AJAX, PHP, and JQuery

Context: I am currently working on a project that involves integrating a Simple Google Map with an HTML form right below it. The form collects user input and upon submission, sends the data via AJAX to a PHP script for processing API calls and generating i ...

Increase the size of the NativeScript switch component

Here is the code I am working with: .HTML <Switch style="margin-top: 10" (checkedChange)="onFirstChecked1($event)" row="0" col="1" horizontalAlignment="center" class="m-15 firstSwitchStyle"></Switch> .CSS .firstSwitchStyle{ width: 30%; ...

The Express.js static() function seems to have trouble serving files from subdirectories that are more than one level deep

My Express.js app has a folder structure displayed on the left. Line 19 utilizes static(). The path for './client' is defined, with path.join() included as well. In the network log on the right, all assets load properly except for the components ...

Is there a way to automatically advance to the next question in Surveyjs without needing to click the Continue

I'm currently integrating SurveyJs into my web application. The first 3 pages of my survey contain HTML elements that I would like to automatically slide after a few seconds, similar to the functionality on the following sample site using SurveyJS: O ...

Decoding JSON Data in Angular 2

I am facing a challenge where I have an array of JSON objects that need to be parsed into my Tournament class. The Tournament class has the following structure: export class Tournament { constructor (public id: number, public name: string, ...

Capture microphone and audio in a SIP call with sip.js

Greetings Stack Overflow community! I am in need of assistance with a project involving sip.js and VoIP for making real phone calls. The Objective I aim to enable users to record audio from both parties during a call and save the data on a server (either ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

Steps for aligning items in a column horizontally in Bootstrap 5

After creating a Grid system with only 2 columns, I placed text in the first column and a carousel in the second. Despite setting a custom size for the carousel image, I'm facing difficulty centering it horizontally within the column. .title-sec { ...

Update a roster with AJAX following the addition or removal of a user

My goal is to implement two functions: Adding and Deleting a User from the database using Mongoose. However, when I run the code, I receive a 200 OK response but with an empty username. I suspect there might be an issue with the ajax calls. Can anyone hel ...

Setting default values for route parameters in JavaScript

I'm looking to streamline my JavaScript code by simplifying it. It involves passing in 2 route parameters that are then multiplied together. My goal is to assign default values to the parameters if nothing is passed in, such as setting both firstnum ...

Refreshing jQuery via Ajax Response

In our JSF2 application, we encounter situations where we need to re-invoke the JavaScript (specifically jQuery for UI styling) when making Ajax calls. However, it seems that the JavaScript functions are not being called upon receiving the Ajax response fr ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

Identifying circular interdependencies within a project

Recently, I encountered an issue with circular dependencies in my project. While I was able to resolve it, I would like to prevent this from happening again in the future. I am considering creating a plugin that can detect circular dependencies throughout ...