Tips on using dual drop-down menus for sorting options

I am encountering a small issue with my two filters.

When I choose the values IN and ENCODE, all the values are displayed correctly...

https://i.sstatic.net/Uoido.png

However, the problem arises when I click on OUT, as the status is not displayed correctly...

https://i.sstatic.net/SoaYG.png

Could you please provide some guidance on how to resolve this issue?

Below is the code that I am working with:

HTML - ANGULAR

<div class="row row-cols-3 pt-3">
  <div class="col text-end">
    <label for="type" class="form-label">Type</label>
  </div>
  <div class="col-4">
    <select
      class="form-select"
      style="max-width: 100px"
      [ngModel]="selectedType"
      (ngModelChange)="onChangeType($event)"
    >
      <option [value]="'ALL'">TOUS</option>
      <option [value]="'IN'">IN</option>
      <option [value]="'OUT'">OUT</option>
    </select>
  </div>
</div>

<div class="row row-cols-3 pt-3">
  <div class="col text-end">
    <label for="type" class="form-label">Status</label>
  </div>
  <div class="col-4">
    <select
      class="form-select"
      style="max-width: 100px"
      [ngModel]="selectedStatut"
      (ngModelChange)="onChangeStatut($event)"
    >
      <option [value]="'ALL'">TOUS</option>
      <option [value]="'1'">ENCODE</option>
      <option [value]="'8'">ANNULE</option>
      <option [value]="'9'">FAIT</option>
    </select>
  </div>
</div>

TS

export class CustomerTransfertComponent implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject<void>();

  customerTransferts: CustomerTransfert[] = [];
  filteredCustomer: CustomerTransfert[] = [];

  constructor(
    private service: CustomerTransfertService,
    private modalService: BsModalService
  ) {}

  ngOnInit(): void {
    this.getCustomerTransfert();
  }

  ngOnDestroy(): void {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  /* Display datas for the HTML table  */
  private getCustomerTransfert(): void {
    this.service
      .getCustomerTransfert()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe((res) => {
        this.customerTransferts = res.PREA.map((val) => {
          return {
            cler: val.CLER,
            num: val.NUM,
            ref_rbc: val.REF_RBC,
            type: val.TYPE,
            quantite: val.QUANTITE,
            isin: val.ISIN,
            trade_date: val.TRADE_DATE,
            reception_date: val.RECEPTION_DATE,
            statut: val.STATUT,
            label: val.LABEL,
            svm: val.SVM,
            coursMoyenAchat: val.COURS_MOYEN_ACHAT,
            personneContact: val.PERSONNE_CONTACT,
            tel: val.TEL,
            fax: val.FAX,
            date: val.DATE,
            traitementDate: val.TRAITEMENT_DATE,
            annulationDate: val.ANNULATION_DATE,
            intitule1: val.INTITULE1,
            contrepartie: val.CONTREPARTIE,
            tis: val.TIS,
            statut_lib: val.STATUT_LIB,
            changement_benef_eco: val.CHANGEMENT_BENEF_ECO,
          };
        });
        this.filteredCustomer = this.customerTransferts;
      });
  }

  public selectedType: any;
  public onChangeType(type: any) {
    this.selectedType = type;
    this.filteredCustomer = this.customerTransferts.filter(
      (item) => item.type === this.selectedType || this.selectedType === "ALL"
    );
  }

  public selectedStatut: any;
  public onChangeStatut(statut: number) {
    this.selectedStatut = statut;
    this.filteredCustomer = this.customerTransferts.filter(
      (item) =>
        item.statut === +this.selectedStatut || this.selectedStatut === "ALL"
    );
  }
}

Any help or advice you can provide on this matter would be greatly appreciated.

Answer №1

Consider applying all filters simultaneously. The variable this.customerTransfers remains unchanged, while this.filteredCustomer gets replaced every time an option is selected.

public selectedType: string;
public onChangeType(type: string) {
    this.selectedType = type;
    this.applyFilters();
}
    
public selectedStatut: string;
public onChangeStatut(statut: string) {
    this.selectedStatut = statut;
    this.applyFilters();
}

private applyFilters() {
   this.filteredCustomer =
       this.customerTransfers.filter(
           (item) =>
               (this.selectedStatut === "ALL"
               || item.statut == this.selectedStatut)
               && (this.selectedType === "ALL"
               || item.type == this.selectedType)
       );
}

Answer №2

When handling the onChange event, ensure you are passing the event object itself rather than just reading the value directly.

Consider using the following syntax:

  1. (ngModelChange)="onChangeType($event.target.value)"
  2. (ngModelChange)="onChangeStatut($event.target.value)"

Additionally, it appears that while you mention the status should be an integer, the options values are being passed as strings. Converting these values to integers may help resolve any issues.

<option [value]="ALL">TOUS</option>
<option [value]="1">ENCODE</option>
<option [value]="8">ANNULE</option>
<option [value]="9">FAIT</option>

Before passing the value to your change function, consider parsing the string value to an integer:

(ngModelChange)="onChangeStatut(parseInt($event.target.value))"

Keep in mind that you may need to handle the case for 'ALL' separately since it cannot be converted to an integer.

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

Are these 2 components very similar, with the only distinction being the unique GET request for each? Should we combine them into one?

There are currently two components in my project that are nearly identical. The HTML structure and CSS rules are the same, with the only difference being the GET request made in the mounted() lifecycle hook. One component fetches all visited places, while ...

Iterating over the local storage to locate a specific item

Utilizing local storage extensively has been beneficial for maintaining state by storing the session on the client side. However, a challenge arises when updating the session. Within my code, there are multiple lists of objects that I serialize in JSON fo ...

Tips for creating a nested array in Javascript:

Given the following: var person = {name: "", address: "", phonenumber: ""} I am trying to implement a loop to gather user input (until they choose to stop inputting information by entering nothing or clicking cancel). My goal is to utilize the person obj ...

The function is triggered by the button depending on its origin

Within my Header component, I have both a "create" and "search" button. This header is included on the customer, products, and sales pages. My question is how can I implement functions for creating and searching specific to each page. Do I need to create ...

Optimizing row display for each page with Material UI's pagination feature

I've been attempting to utilize Material UI table pagination to show 5 rows per page, but for some reason it displays all items on the page and doesn't switch between pages. I'm having trouble figuring out where I'm going wrong. To help ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

Leveraging client-side routes in conjunction with page templates retrieved from Contentful

Objective In an effort to restrict access to certain content under a specific URL (/dashboard), I am exploring the use of client-only routes. This content, sourced from Contentful and utilizing a page template, will follow a route structure like {MYDOMAIN ...

Steps for opening a modal in a react native application when a button is clicked

Exploring the realm of react native, I face a challenge in triggering a modal on button click. I've attempted to implement the following code snippet to achieve this goal:- openHeaderModal = () => { <ModalDropdown options={["H1", "H ...

Expanding the table to display additional rows using pagination in an Angular application

I have implemented a table in Angular that displays data fetched from an API. The requirement is to initially display only the first 5 rows and provide an option for users to view more rows (in groups of 5) with pagination support. Below is the code snipp ...

There seems to be an issue with ngOptions in Angular as it is

Calling all angularjs experts for assistance... Currently integrating cake with angular. Utilizing a rest controller to enable communication and retrieve options in a serialized json format as displayed below Attempting to populate dropdown options: &l ...

Module '../../third_party/github.com/chalk/supports-color' not found in the directory

Within my tutoring-frontend-main project folder There is a file named package.json { "name": "app-frontend", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "n ...

Storing information in an array with automatic ID generation_incrementing

Here is an array in a specific format, however, there is no "ID" field available when the form is submitted. The requirement is to have an auto-generated ID assigned and saved in a JSON Array upon user submission of the form. With each form submission, t ...

What could be causing html-webpack-inline-source-plugin to prevent the page from refreshing after editing CSS files?

Currently, I am utilizing a plugin that embeds all CSS within the final HTML file. This method prevents the application from refreshing in development mode. Whenever I make edits to the CSS, the build process completes normally, but the styles do not updat ...

Using JavaScript drag and drop feature to remove the dragged element after a successful drop operation

Trying to figure out how to remove a dragged element from the DOM after a successful drop using the native JavaScript drag and drop API. After attempting to listen for the drop event, it seems that it only fires on the element being dropped onto and does ...

"An issue arises as the variable this.results.rulesFired is not properly

I am faced with a set of table rows <tr *ngFor="let firedRule of splitRules(results.rulesFired); let rowNumber = index" [class.added]="isAdd(firedRule)" [class.removed]="isRemove(firedRule)" ...

I am attempting to retrieve a value from a dropdown menu but I am encountering difficulties

Within the structure of a Vue component's template, I have the following code: <td> <select id="papel" @change="intervChange(row)"> <option value="Apreciador">Apreciar</option> <option value="Assessor">Assessor ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Select the small image to reveal the larger overlay image

I have a grid of images and I want each image to expand into fullscreen when clicked. However, the JavaScript I am using is causing only the last image in the grid to overlay. How can I resolve this issue? Here is the code I am currently using: http://js ...

Implementing updates to a particular value in a sub-document in Cosmos DB using Azure Function and TypeScript

I am looking to update a specific value called statutProduit in a sub-document residing within a document collection in Azure Cosmos DB. This will be accomplished using an HttpTrigger Azure Function that requires two parameters: the document ID (id) and th ...

A guide on enabling or disabling a combobox in vuejs3

In VueJs 3, I am looking for a way to toggle the Disable/Enable status of a combo-box based on a specific property. Below is my code snippet: <template> <div class="combobox"> <label for={{selector_name}}> <p> ...