Filters cascade data sourced from an API

My goal is to create a cascading filter that retrieves data from an API. Each time a user selects an item from the Transaction Type Dropdown, it triggers the getTransactionSubType function. The selected item in the Transaction Type Dropdown becomes the

this.payloadFilter.transactionType
, which is used as a parameter to fetch data from getTransactionSubType and display it in the Transaction Sub Type.

I'm not entirely confident in the current implementation as I've noticed some delays in retrieving the transaction sub-type data when changing or selecting items in the transaction type. Is there a better way to approach this problem?

Any help or suggestions would be greatly appreciated. Thank you.

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

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

#html code

<div class="report-filter-container">
      <div class="report-select-container">
        <mat-form-field appearance="fill" class="full-width">
          <mat-label>Transaction Type</mat-label>
          <mat-select 
            multiple
            #selectElemTransactionTypes
            [(value)]="reportFilter.transactionType"
            (selectionChange)="changeFilter('transactionType',selectAllTransactionTypes)"> `
            <div class="idle-report-select-all-container">
              <mat-checkbox
                #selectAllTransactionTypes
                color="primary"
                (click)="toggleAllSelectionFilter('transactionType',selectElemTransactionTypes, selectAllTransactionTypes)">
                  Select All
              </mat-checkbox>
            </div>
            <mat-option *ngFor="let f of filters.transactionType" [value]="f.name">
              {{f.name}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>
      
      <div class="report-select-container">
        <mat-form-field appearance="fill" class="full-width">
          <mat-label>Transaction Sub Type</mat-label>
          <mat-select 
            multiple
            #selectElemTransactionSubTypes
            [(value)]="reportFilter.transactionSubType"
            (selectionChange)="changeFilter('transactionSubType',selectAllTransactionSubTypes)"> `
            <div class="idle-report-select-all-container">
              <mat-checkbox
                #selectAllTransactionSubTypes
                color="primary"
                (click)="toggleAllSelectionFilter('transactionSubType',selectElemTransactionSubTypes, selectAllTransactionSubTypes)">
                  Select All
              </mat-checkbox>
            </div>
            <mat-option *ngFor="let f of filters.transactionSubType" [value]="f">
              {{f}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>

Hi, I am trying to implement a cascading filter whose data comes from an API. So every time a user selects from the

#Ts code

ngOnInit(): void {
  this.getTransactionType();
  this.getTransactionSubType();
}

toggleAllSelectionFilter(selectProp: string, selectElem:MatSelect, selectAll: MatCheckbox) {    
  let isSelectAllSelected = this.isAllSelected[selectProp];
  const checkSelAllOption = !isSelectAllSelected;
  selectElem.options.forEach((item: MatOption) => (checkSelAllOption)? item.select(): item.deselect());
  this.isAllSelected[selectProp] = checkSelAllOption;   
  setTimeout(()=>{
    selectAll.checked = checkSelAllOption;
  },0)    
}

changeFilter(filterName:string, selectAll: MatCheckbox){    
  this.isAllSelected[filterName] = (this.reportFilter[filterName].length === this.filters[filterName].length);
  this.payloadFilter[filterName] = JSON.stringify(this.reportFilter[filterName]);
  selectAll.checked = this.isAllSelected[filterName];

  if(filterName === 'transactionType') {
    this.getTransactionSubType();

  }
}

getTransactionSubType(){
  let payloadFiltertransactionType = JSON.parse(this.payloadFilter.transactionType);
  this._transSubTypeService.getTransactionSubtype(this.accountName,payloadFiltertransactionType)
  .subscribe(
    res =>{                
      if (res.isSuccess) {
        this.filters.transactionSubType = res.data;
      }
    },
    err => {
      this.dialog.closeAll();
      this._notificationService.showError('Encountered an error. Please try again.');
    }
  )
}

Answer №1

If you need to retrieve dynamic data based on the first dropdown selection, then your current implementation is sufficient.

However, there are opportunities for improvement such as:

  1. Avoid pre-populating transaction subtypes and only load them when a selection is made from the first dropdown.

  2. Consider displaying a full-screen loader when updating the first dropdown until the subtypes are fetched, or incorporate a loader within the dropdown itself.

  3. Explore implementing caching mechanisms for improved performance.

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

I am constantly encountering the error message "Reading 'Linear'' error due to undefined properties in my threejs code

A procedural generation library for threejs caught my attention Here is the link to the library: https://github.com/IceCreamYou/THREE.Terrain Despite following the instructions provided in the ReadMe.md file, I encountered an error that says: Cannot read ...

A guide to looping through a JSON array

After utilizing the Gson library to generate a JSON from Java, the output I receive is as follows: [{"title":"title1","author":"author1"},{"title":"title2","author":"author2"}] What would be the most effective approach for parsing and accessing these val ...

Combine two functions into a single one to streamline and avoid overlap

Recently, I set up an exclusive checkbox feature within my HTML code. This feature includes 2 <input> elements along with two <button> elements that are also exclusive and have black/white color options based on the input they are associated wi ...

Transitioning to Angular - The hybrid application is not being bootstrapped

Attempting to transition my AngularJS 1.6 application to Angular 7 using the ngUpgrade route has hit a roadblock. Upon trying to bootstrap my hybrid application, it fails to execute my main.ts file despite being set as the entry point in the webpack config ...

Change the class of <body> when the button is clicked

One of my tasks involves adding a button that, when clicked, should give the body the class "open-menu". Implementing this using jQuery was quite straightforward - I just needed to add the following line of code: $('.burger').click(function() ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...

What is the best way to incorporate a logo container and a horizontal divider into my top navigation bar using Bootstrap?

I'm currently working on designing a top navigation bar that features a logo with color #1 as the background on the left side. The logo is then separated by a grey horizontal divider, followed by color #2 representing the application name beside the d ...

Strategies for avoiding text selection interference with onMouseMove event

I am in the process of adding a "resize handle" to adjust the width of my left navigation panel. This handle, represented by a div, triggers an onMouseDown() event that calculates the necessary widths and applies them to the relevant elements during subseq ...

"Exploring the Power of Primefaces Dialog Framework: Unleashing the dialogReturn Event

I'm working with a primefaces p:datatable in Table.xhtml and have a p:commandbutton on the same page that triggers a dialog using the dialog framework. The dialog content is in Dialog.xhtml. Both the Table.xhtml and Dialog.xhtml are using a single bac ...

Tips on traversing a JSON array in AngularJS using the ng-repeat directive

My service returns the following JSON data: {"categories":[{"category_id":"20","name":"Desktops"}, {"category_id":"18","name":"Laptops &amp;"},{"category_id":"25","name":"Components"}, {"category_id":"57","name":"Tablets"}, {"category_id":"17","name": ...

Show or conceal a group of div elements

I previously sought assistance on how to make my show/hide function work, and I am grateful for the help that solved my issue. However, I am now facing a new challenge in displaying a set of divs. Specifically, I have 4 divs, each with a unique ID and cla ...

Retrieving the title property with the power of JavaScript

https://i.sstatic.net/cp7qK.png My journey into JavaScript is just beginning, and I'm currently immersed in a project that involves using facial recognition technology to detect emotions. While the software successfully detects emotions, I am struggl ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

A dynamic d3 line chart showcasing various line colors during transitions

I have implemented a d3 line chart using this example as a reference: https://codepen.io/louisemoxy/pen/qMvmBM My question is, is it possible to dynamically color the line in the chart differently based on the condition y > 0, even during the transitio ...

Styling not being applied in Angular directive

Seeking assistance with styling AngularJS directives, specifically a Bootstrap directive for progress bars within my project. Utilizing it within a custom div class. <div class="diagnostics-widget-modal"> <div class="modal-header"> ...

Is it possible to replicate a slow image loading experience in React.js?

Referenced the solution below How to simulate slow loading of image Slowing down internet connection with Chrome DevTools works, but the entire site loads slowly. I want to specifically focus on slowing down the image reloading. One of the suggestions w ...

Retrieve PDF files from mongoDB and render them in an HTML format

After successfully uploading a PDF to mongoDB, I encountered an issue with reading and displaying it. To read the uploaded PDF, I converted it using the following code: var buf2 = new Buffer(data).toString('base64'); The resulting format of th ...

Can a dynamic form action be achieved?

My toolbar has 3 buttons (delete, block, unblock). Is it possible to dynamically change the form action? <form action="/users/groupUnblock" method="POST"> <button type="submit" class="btn btn-danger btn-sm" ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Styling with CSS to position a div tag on top of a webpage

I have a calendar code inside a div and I want to display the calendar when clicking an anchor tag without sliding the entire div. Currently, it is displayed as: However, I want it to be displayed as shown in the next image: <a class="aastext"&g ...