The data in the filtered table is failing to revert back to its original state upon removing the filtered item from the webpage

I am currently working with an ng-multiselect dropdown to fetch data from a database. These dropdowns are being used to filter a data table on a webpage. However, I am facing an issue where when a dropdown item is selected, it correctly filters the table, but upon un-selecting the item, the data table does not return to its initial state. As a solution, I need to implement a condition so that when an item is un-selected, the table data goes back to its original state.

.ts

  
tableData: ITransactionDetail[];
data: ITransactionDetail[];

selectedItems = [];
selectedIds = [];

dropdownSettings: IDropdownSettings;

this.dropdownSettings = {
singleSelection: false,
idField: 'id',
textField: 'transactionType',
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
itemsShowLimit: 3,
allowSearchFilter: true
};

onItemSelect(item: any) {
this.selectedIds.push(item.id);
this.resetTable();
}
onSelectAll() {
this.selectedIds = this.data.map(x => x.id);
this.resetTable();
}
onDeSelectAll() {
this.selectedIds = [];
this.resetTable();
}
onItemDeSelect(item: any) {
this.selectedIds.splice(this.selectedIds.indexOf(item.id), 1);
this.resetTable();
}
resetTable() {
this.tableData = [...this.data.filter(x => this.selectedIds.includes(x.id))];
} 

.html

      
<th mat-header-cell *matHeaderCellDef>
transactionType
<div>
<ng-multiselect-dropdown
[placeholder]="'Select'"
[settings]="dropdownSettings4"
[data]="data"
(onSelect)="onItemSelect($event)"
(onSelectAll)="onSelectAll($event)"
(onDeSelect)="onItemDeSelect($event)"
>
</ng-multiselect-dropdown>
</div>
</th>
<td mat-cell *matCellDef="let element">{{ element.transactionType }}</td>

Answer №1

Take a look at this alternative approach:

handleDeselectAll() {
    this.selectedIds = [];
    this.tableData = [...this.sourceData];
}

onItemUnselect(item: any) {
   this.selectedIds.splice(this.selectedIds.indexOf(item.id), 1);
   if (this.selectedIds.length > 0) {
     this.resetTable();
   } else {
     this.tableData = [...this.sourceData];
   }
}

See the 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

The functionality of System.import is native to JavaScript and is a feature exclusive to Angular 2

I have been examining the sample code for the Hello World quick start angular 2 app below. Query Is the System.import in the Hello World quick start angular 2 app a JavaScript statement/construct or a function specific to angular 2? If it belongs to Jav ...

Exploring Angular2: A guide to incorporating dynamic properties with conditional logic

Currently, I am diving into Angular2. In the midst of my journey, I am facing the challenge of adding a property to a <select> only if the class property type is 'withName' If this condition holds true, the outputted select should be: < ...

Why am I encountering a 400 error with my mutation in Apollo Client, when I have no issues running it in Playground?

After successfully testing a mutation in the playground, I attempted to implement it in my Apollo client on React. However, I encountered an error message stating: Unhandled Rejection (Error): Network error: Response not successful: Received status code 40 ...

The debate between using "this" versus "classname" to access static elements in

When working with TypeScript, I've observed that there are multiple valid approaches for accessing a static class member. class MyClass { private static readonly FOO: string = "foo"; public DoSomething(): void { console.log(MyClass.FOO);} pu ...

Creating an Angular reactive form with checkboxes and initializing a formArray with an existing array

I have a dynamic array of LkBoardTypeList fetched from a server. My goal is to push that array to form an array upon initialization, essentially displaying checkboxes based on the Board's name or ID in the array. I know how to push an empty array in r ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Utilizing the power of d3.js within Angular 4

Currently, I have successfully implemented code to draw a polygon using the mouse in a normal JavaScript file. Now, I am looking to replicate the same functionality in my TypeScript file. Below is an excerpt from my d3.js file: //D3.JS VERSION 3 //------ ...

How to access a static TypeScript variable in Node.js across different files

I encountered a situation like this while working on a node.js project: code-example.ts export class CodeExample { private static example: string = 'hello'; public static initialize() { CodeExample.example = 'modified'; } ...

Is there a way to show a string value stored in Java onto an Angular 8 display?

Hey there! I am just starting out with angular 8 and have a java project where I'm using JDBC to connect to my beloved MySQL database. I have some valuable data stored in a MySQL table that I access in java and store in strings (or even a list). Now, ...

Is there a reason for TypeScript compiler's inability to effectively manage filtering of nested objects?

Perhaps a typical TypeScript question. Let's take a look at this simple filtering code: interface Person { id: number; name?: string; } const people: Person[] = [ { id: 1, name: 'Alice' }, { id: 2 }, { id: 3, name: 'Bob&apos ...

Develop a type definition utilizing dotted paths from a recursive object model

Working with TypeScript, I am dealing with a nested object structure of functions defined as: type CallbackFn = (args: any) => any type CallbackObj = { [key: string]: CallbackFn | CallbackObj } const callbacks = { foo: function(args: { x: num }): st ...

undefined event typescript this reactjs

I have come across the following TypeScript-written component. The type definitions are from definitelytyped.org. I have bound the onWheel event to a function, but every time it is triggered, this becomes undefined. So, how can I access the referenced el ...

Encountering a NgForm provider error in Angular 4.4.6 development mode

UPDATE: Identifying the root of the issue has led me to search for a suitable solution. NOTE: This complication is specific to development mode (not production, and not utilizing AOT). The "Update" resolution I am implementing can be found here. In an a ...

Exploring advanced customization options in Angular 6+: Extending the default configuration beyond the environment settings

I am dealing with multiple Angular configurations and I'm trying to customize the default settings by using lodash merge: import { merge } from 'lodash' import { defaults } from './defaults' export const customConfig = merge(defa ...

Facing Issues with HTTP Headers in Express or Node?

I have developed an Express/NodeJS REST API that includes setting a custom header on the response: router.route("/api/articles") .get(authCheck, function (req, res) { let pagination = req.get('Pagination').split(","); let cur ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Leveraging React Hooks to display a dynamic pie chart by fetching and mapping data from an API

I have a task where I need to fetch data from an API that returns an object containing two numbers and a list structured like this... {2, 1 , []} The project I'm currently working on utilizes 'use-global-hook' for managing state in Redux. T ...

Tips for customizing the main select all checkbox in Material-UI React data grid

Utilizing a data grid with multiple selection in Material UI React, I have styled the headings with a dark background color and light text color. To maintain consistency, I also want to apply the same styling to the select all checkbox at the top. Althou ...

What steps can I take to achieve complete code coverage in my unit testing for this component and also ensure that the 'else' part is being

I am struggling to figure out how to access the remaining line of code in order to achieve full code coverage. Simply checking if the function has been called (toHaveBeenCalled()) will suffice. Here is a snippet from my TypeScript file and Spec file, alon ...

The NestJS framework encountered an error due to a method being undefined in the

Encountering Error with NestJS Function create123: TypeError - Cannot read properties of undefined (reading 'create123') The constructor is displayed below \`export class AuthenticationService { constructor( private readonly usersServ ...