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

Creating an animated background slide presentation

After creating a button group, I wanted the background of the previous or next button to move/slide to the selected one when the user clicks on it. I achieved this effect using pure CSS and simply adding or removing the 'active' class with jQuery ...

Looking to modify the CSS of an element during a drop event using interact.js?

I've encountered an issue in my code where setAttribute and .transform are not working as expected. I have tried using them within the ondrop event function, but with no success. interact('.dropzone') .dropzone({ // Setting the r ...

Can the JavaScript code be altered within the client's browser?

So, I'm using JQuery Validator on my webform to validate form data. However, I haven't added any validation on the server side. I'm curious if it's possible for a user to modify the code and bypass my validations in their browser. If th ...

Managing headers for localhost with Access-Control-Allow-Origin

I've run into a challenge with my React app. I'm making endpoint calls to different servers and have withCredentials set to true to include a token/cookie in the requests. The issue arises when trying to make this work seamlessly on localhost. S ...

Tips on automatically changing the background image every few seconds

As a newcomer to Angular and programming in general, I am facing an issue with changing the background image of my Page using the setInterval method. The intended behavior is for it to change every second, but for some reason, it changes much faster than t ...

What steps can I take to determine the status of my Axios post request?

Here's a simple task I'd like to accomplish using Axios for an Ajax request. When a user clicks on a button, I want to fire an Ajax request. While the request is processing or until it's completed, I would like to disable the button or impl ...

Array vs Single Object - Comparing AngularJS / Javascript Data Structures (Basic)

My array is very basic [ { ticketId: 1, name: "John", }, { ticketId: 124, name: "Ads" } ] I have displayed the data in a dropdown menu <ul class="dropdown-menu"> <li ng-repeat="ticket in tickets"> <a h ...

Angular is experiencing difficulty locating the routing path for the auxiliary `router-outlet`

Exploring the intricacies of routing in Angular to gain a deeper understanding of the concept. Encountering an issue where I am receiving an exception NG04002: Cannot match any routes. URL Segment: 'about' when attempting to click on the About li ...

Transitioning from the traditional LeftNav menu style to the more versatile composability feature using Reactjs with Material-ui

Hey there, I'm facing a bit of confusion while trying to create a LeftNav menu using material-ui. I recently joined this project and updated reactjs and material-ui. Unfortunately, many things related to LeftNav in material-ui have been deprecated, ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function(); var viewController = new Vue({ el: "#app", ...

Creating a unique filter that combines and filters data from two separate API calls for

In my current scenario, I am making two different API calls using Axios in my application. The first call fetches a complete JSON file that populates a table, while the second call retrieves only categories. This setup is due to the complexity of the app, ...

The Problem with AJAX Error Handling Customization

Upon loading my webpage using Code Igniter and PHP, the JSON encoded query is returned successfully with data. I have managed to handle the scenario where no records are found by encoding a response in JSON format. However, I am unsure of how to transmit t ...

When using ng-repeat with Angular ui-bootstrap and tabs, the new tab will not be selected if there are no existing tabs present

To showcase the problem I'm facing, please refer to this link: http://codepen.io/pietrofxq/pen/ZLLJdr?editors=1010 Click on "remove tabs" and then on "add tab" The challenge at hand involves using a loop with ng-repeat to display tabs. At times, the ...

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

Object.assign changes the original array object in place

I am facing a challenge while attempting to modify the value of a specific index in my state, specifically the property post_comments. The issue lies in the fact that even though I am only modifying a copy of the state, the actual state is also being alter ...

What could be causing my view to not update?

Within the code snippet below, I am subscribing to an observable and storing the value of result in the status variable. This variable is then used in an *ngIf statement in the view. However, even when the value is true, the view does not update accordingl ...

Utilizing a .ini file to assign variables to styles elements in Material-UI: A comprehensive guide

I need to dynamically set the background color of my app using a variable retrieved from a .ini file. I'm struggling with how to achieve this task. I am able to fetch the color in the login page from the .ini file, but I'm unsure of how to apply ...

Angular2: AuthGuard malfunctioning with browser navigation controls

My AuthGuard setup works flawlessly during normal navigation within the application (see code below). Now, consider this scenario: A user goes to /content/secured-content, which requires authentication => they are redirected to /authentication/login due ...

Open the HTML page from a separate directory

I'm facing an issue with loading additional HTML onto a page in my project when a link is clicked. The HTML fragment file I want to load is stored in a different folder within the project structure. Despite my efforts, I keep encountering a 404 error ...