Filtering the data in the table was successful, but upon searching again, nothing was found. [Using Angular, Pagination, and

Having a table with pagination, I created a function that filters the object and displays the result in the table.

The issue arises when I perform a new search. The data from the initial search gets removed and cannot be found in subsequent searches.

Below is the code snippet for my sort function:

export class TaxreportsComponent implements OnInit {

  public taxList: Array<Tax>;
  public page: number;
  public currentPage: Array<Tax>;
  public totalItems: number;

  constructor(private service: CompanyService) {
    this.totalItems = 0;
    this.currentPage = [];
    this.taxList = [];
    this.page = 1;
  }
  ngOnInit() {
    this.service.getTaxList((data) => this.onGetTaxList(data));
  }
  onGetTaxList(data) {
    this.taxList = data;
    this.currentPage = this.taxList.slice(0, 10);
    this.totalItems = this.taxList.length;
  }
  pageChanged(event) {
    const startItem = (event.page - 1) * event.itemsPerPage;
    const endItem = event.page * event.itemsPerPage;
    this.currentPage = this.taxList.slice(startItem, endItem);
  }

// Sort the data and update the table
  sort(searchWord) {
    const data = this.taxList.filter(item => {
      return item.type === searchWord;
    });
    this.onGetTaxList(data);
  }

Here is the HTML code:

<app-home-menu (filteEvent)="sort($event)" ></app-home-menu>
<div class="table-container">
  <table class="table">
    <thead>
      <tr class="table-nav">
        <th scope="col">Year</th>
        <th scope="col">Type</th>
        <th scope="col">HP</th>
        <th scope="col">CompanyName</th>
      </tr>
    </thead>
    <tbody>
      <ng-container *ngFor="let tax of currentPage">
        <tr>
          <td>{{tax.year}}</td>
          <td>{{tax.type}}</td>
          <td>{{tax.cid}}</td>
          <td>{{tax.company}}</td>
        </tr>
      </ng-container>
    </tbody>
  </table>
  <div class="table-footer">
  <pagination class="pagination" nextText=">" previousText="<"  [totalItems]="totalItems" (pageChanged)="pageChanged($event)"> </pagination>
</div>
</div>

It is essential to initialize the original object before each new search. I need to find a solution for this.

Answer №1

It's important to note that using only one variable (taxList) for data may result in the loss of actual data when filtering. To prevent this, consider introducing a separate variable (filteredTaxList) specifically for filtered data.

When receiving actual data from the service, store it in the taxList and then set filteredTaxList to reference it. This way, the original data is preserved.

For each filter change, update filteredTaxList based on the current taxList content.

Ensure to utilize the new variable (filteredTaxList) throughout the code, including for tasks like pagination.

export class TaxreportsComponent implements OnInit {

  public taxList: Array<Tax>;
  public filteredList: Array<Tax>;
  public page: number;
  public currentPage: Array<Tax>;
  public totalItems: number;

  constructor(private service: CompanyService) {
    this.totalItems = 0;
    this.currentPage = [];
    this.taxList = [];
    this.filteredList= [];
    this.page = 1;
  }
  ngOnInit() {
    this.service.getTaxList((data) => this.onGetTaxList(data, true));
  }
  onGetTaxList(data, isOriginal) {
    if(isOriginal) this.taxList = data;
    this.filteredtaxList = data;
    this.currentPage = this.filteredtaxList.slice(0, 10);
    this.totalItems = this.filteredtaxList.length;
  }
  pageChanged(event) {
    const startItem = (event.page - 1) * event.itemsPerPage;
    const endItem = event.page * event.itemsPerPage;
    this.currentPage = this.filteredTaxList.slice(startItem, endItem);
  }

// Sort the data and change the table
  sort(searchWord) {
    const data = this.taxList.filter(item => {
      return item.type === searchWord;
    });
    this.onGetTaxList(data, false);
  }

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 distinctive, unchanging colors for individual ellipses within a collection in p5.js

It's clear that each ellipse is part of a wave object, with the fill color applied on every frame causing a blinking effect. I'm trying to assign a random color to each ellipse when it's drawn, so it maintains that fill color instead of chan ...

Can the keypress event be modified within the Google Chrome browser?

My code is functioning in IE but not in Chrome. I am having issues with the event not changing. Is there a different method for achieving this in Chrome, rather than assigning specific values to the charCode, keyCode, and which variables? You can view my ...

When setting a value through the DOM, the input's value bound with ngModel in Angular does not get updated

Trying to upload a file to calculate its hash and display it in an input box. If done correctly, the value should show in the form, but when submitting the form, the value does not get sent. Only adding a blank space by clicking on the input field works: ...

Select a single radio button containing values that can change dynamically

<input type="radio" on-click="checkDefaultLanguage" id="checkbox" > [[names(name)]] This custom radio input field contains dynamic values and I am attempting to create a functionality where only one radio button can be selected at a time while dese ...

What is the best way to update setState when triggering an onChange event?

Here is the code snippet for a React component that handles cryptocurrency selection: import React, { Component } from 'react'; import { Select } from 'antd'; import { connect } from "react-redux"; class SelecionarCrypto extends Compo ...

Redirecting based on conditions in Angular 2+ with wildcard paths

I have a variety of paths, each corresponding to a specific stage in a wizard. const routes: Routes = [ { path: ':id', component: ParentComponent, children: [ {path: 'step1', component: Step1Component}, {path: ...

The execution of a new observable is delayed by using RxJS's switchMap

I've encountered a challenge in my Angular project where I need to handle HttpClient calls and depending on the response from the first call, decide whether to make another call with a delay. I am familiar with using the switchMap operator for this pu ...

What is a way to hide or exclude tabs when there is no content to display for a particular tab in Vue?

I'm new to javascript and Vue, and I'm trying to figure out how to hide tabs that don't contain any information. I want to display only the tabs that do have information. Can someone please help me with this? I automatically pull images bas ...

Header stabilization on scroll

On my webpage, I have a table header positioned in the middle of the page. However, due to the length of the page, I am looking for a way to make the header stay fixed at the top of the browser as the user scrolls down. My query is: Is there a method to k ...

Having trouble with data retrieval from MySQL using PHP and Angular on certain mobile devices, although it functions properly on desktops and laptops

The data retrieved from the mysql database is functioning properly on desktop and laptop, but not on mobile devices. The following HTML code is present in the html file: <table class="table table-default"> <thead> <tr> & ...

The method Office.context.mailbox.item.internetHeaders.setAsync has not been configured

I am integrating the Microsoft Office API into Outlook. I'm attempting to add an extra x-header to my email in the composer scope for later identification. To achieve this, I referred to the following documentation: https://learn.microsoft.com/en-us/j ...

Guide to embedding bootstrap.min.js into ember-bootstrap extension

I'm currently experiencing an issue with the ember-bootstrap plugin. Following the instructions on their setup page at , I downloaded and installed it. Once I began working on the Navbar, I encountered a problem. The Hamburger menu, which is supposed ...

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...

Managing websites on Android when the keyboard is displayed

I am currently facing an issue with my webpage on Android (Galaxy SIII). The problem occurs when visitors try to enter their email in the form at the bottom of the page. The keyboard becomes visible, causing the design to look messy. When using Chrome, the ...

You can see the JavaScript code directly in the browser

I'm completely puzzled as to why this is happening. How strange that the JavaScript code is visible on the browser, almost appearing like regular text on the web page. This mysterious occurrence seems to be exclusive to Firefox. Despite scouring vario ...

The element type 'x' in JSX does not offer any construct or call signatures

I have recently imported an image and I am trying to use it within a function. The imported image is as follows: import Edit from 'src/assets/setting/advertising/edit.png'; This is the function in question: function getOptions(row) { ...

"Implementing a Texture as Material in Three.js: Step-by-Step Guide

I recently discovered Three.js and I'm really enjoying it. As a newcomer to JavaScript, I'm eager to delve deeper into animation and related topics. //UPDATE I've been working on this code snippet, but unfortunately, it's not functioni ...

Exploring the differences between Typescript decorators and class inheritance

I find myself puzzled by the concept of typescript decorators and their purpose. It is said that they 'decorate' a class by attaching metadata to it. However, I am struggling to understand how this metadata is linked to an instance of the class. ...

Suggestions for rectifying the calculation script to include the price, a phone number, 2 digits, and integrating a textfield for cost

I have developed a script that calculates prices, phone numbers, and extracts the last 2 digits from the phone number. In my website, the price is displayed through a select option. However, I am facing an issue where the cost does not automatically updat ...

Transforming Typescript Strings into ##,## Format

As I've been using a method to convert strings into ##,## format, I can't help but wonder if there's an easier way to achieve the same result. Any suggestions? return new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, max ...