Is it possible to retrieve the original array after removing filters in Angular?

Within my component, I have an array that I am filtering based on a search string. The filtering works as expected when the user inputs characters into the search field. However, I am encountering an issue when attempting to display all records again after the user clears the search field.

Please review the code snippet below for reference:

 this.filterServ.filterData.subscribe(searchData => {
         if (Object.keys(searchData).length != 0) {
            console.log('component', searchData);
           this.cardData = this.cardData.filter((project) => {
               let name = project.Name.toLowerCase();
               if (name.includes(searchData.searchString.toLowerCase())) {
                  return true;
               }
            });
           console.log('filtered data', this.cardData);
         }
      });

Answer №1

After making changes to the cardData, you cannot undo those modifications.

To resolve this issue, consider adding a new property such as displayData.

You can achieve this by:

this.displayData = this.cardData.filter((project) => {

Then, in your template, use displayData instead of cardData.

Answer №2

Create a field named filterData and connect it to the template.

this.filterServ.filterData.subscribe(searchData => {
         if (Object.keys(searchData).length != 0) {
            console.log('component', searchData);
           this.filterData= this.cardData.filter((project) => {
               let name = project.Name.toLowerCase();
               if (name.includes(searchData.searchString.toLowerCase())) {
                  return true;
               }
            });
           console.log('filtered data', this.cardData);
         }
      });

I hope this information is helpful!

Answer №3

It is important to make a copy of the array data before applying any filters, and if the input text is empty, return the original array.

    let originalArr = this.cardData.slice();

    this.filterServ.filterData.subscribe(searchData => {
         if (Object.keys(searchData).length != 0) {
            console.log('filtering data with search criteria', searchData);
           this.cardData = originalArr.filter((element) => {
               let name = element.Name.toLowerCase();
               if (name.includes(searchData.searchString.toLowerCase())) 
               {
                  return true;
               }
            });
           console.log('filtered result:', this.cardData);
         }
      });

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

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

Is it possible to include spaces in a JavaScript alert message?

Is it possible to add spaces in an alert message? I have been trying to include spaces in my alert messages, but the alerts do not appear when there are spaces. Example where it works: https://jsfiddle.net/yczrhztg/ Example where it doesn't work: ht ...

Tips for utilizing the multiselect() function without deleting current values and incorporating new values determined by another selection

Currently, I am working on an e-learning project that involves managing a large number of student registrations. I have implemented a search box to find students' names and add them to a list. However, I encountered an issue when trying to search for ...

Encountered a discrepancy with npm dependencies during the update or installation process on a legacy project

I am encountering issues while attempting to run an older project. Every time I try to npm install or start the project, it throws various dependency errors, particularly related to the outdated npm version. My current node version is 16.x, whereas the pro ...

Load page content dynamically with Ajax in a specific div while still allowing the option to open the content in a new tab by right-clicking

As I work on developing a new website that utilizes a MySQL database to sort various items into categories and subcategories, I have implemented a script that dynamically loads category content into a div without requiring a page reload. This seamless load ...

React Chart.js allows for consistent spacing for x-axes by displaying dates in a well-organized

After incorporating displayFormats in scales.x, I noticed that my xAxes labels are spaced differently based on the data object they contain. How can I adjust my xAxes labels to have equal spacing? The code snippet is displayed in the following image. Pleas ...

Form a collection of X amount of words using a string in JavaScript

Hello amazing Stack community, I am currently striving to create a straightforward JavaScript function that can accurately count the total number of words from a given string value. Furthermore, I aim to store a specific number, X, of words into an array ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

Adjusting the visible options in ngOptions causes a disruption in the selected value of the dropdown menu

I have successfully implemented a feature that allows users to convert temperature values displayed in a drop-down menu to either Celsius or Fahrenheit. For this functionality, I am using a select input with ng-options as shown below: <select ng-model ...

typescript undefined subscription to observable

After making an http request to fetch some data, I am facing issues in displaying it as intended. The dropdown select for entriesPerPage, and the left and right cursors for switching page in pagination are working fine. However, upon switching a page, I en ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

What is the best way to dynamically adjust the select option?

I need help with handling JSON objects: [ { id: "IYQss7JM8LS4lXHV6twn", address: "US", orderStatus: "On the way", }, ]; My goal is to create a select option for the order status. If the current status is "On ...

Retrieve the current URL upon page load

I'm currently attempting to parse the URL in document.ready() so I can retrieve the id of the current page and dynamically populate it with content from an AJAX call. However, I've encountered an issue where 'document.URL' seems to refe ...

integrating an array into MongoDB using Angular and NodeJS

Encountering an issue with mlab (mongoose), angular.js, HTML, and JavaScript. When passing an array with values from an angular.js controller to the server side (node.js), it fails to insert the data into the schema in mlab. Below is my HTML code: <fo ...

Encountering the "potential null object" TypeScript issue when utilizing template ref data in Vue

Currently, I am trying to make modifications to the CSS rules of an <h1> element with a reference ref="header". However, I have encountered a TypeScript error that is preventing me from doing so. const header = ref<HTMLElement | null> ...

Validation in Sync with Angular 2's Latest Version

Encountering the error 'Expected validator to return Promise or Observable' when trying to implement a custom synchronous validator using FormControl and FormGroup classes for validation. The transition from beta to final release has been baffli ...

After refreshing the page, the ngRoute white page is displayed

I've encountered an issue with my Angular website. I built it using ngRoute, but when I click on a link, a white page appears. Only after refreshing the page does the content actually show up. Even in the browser's DevTools, you can see the html ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Creating a modal dialog using a function in a TypeScript file

Hey there, fellow developers! I have a question that might seem simple. So, in my HTML code I've got a Modal Dialog that pops up using ng2 Bootstrap. It's working fine, but... I want to replace this line of code "<button class="btn btn-prim ...

Loading a div using Ajax within a frame

My php page includes a div that is supposed to be populated by an Ajax call. function showcopay() { var apa = document.getElementById("alert_id").value; $("#copay").load('show_copay.php?pid='+apa); } The parent page of the div used to be ...