How can I dynamically display dropdown options in Angular using PrimeNG based on the selection made in another dropdown?

My goal is to show the nearest store based on a specific location. To achieve this, I have implemented 2 dropdowns - one for selecting the location (states) and the other for displaying the nearest store (tenants). There are a total of 6 locations and only 2 stores available. https://i.sstatic.net/HaDsk.png https://i.sstatic.net/w1OCo.png

Within the .ts file, I first retrieve all the active stores (tenants)

    getAllTenants() {
      this._tenantService.getTenantsForPublic(undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,999,undefined).subscribe((data) => {
        this.tenants = data.items.filter((item) => item.isActive);
      })

}

Next, I retrieve all the locations (states)

  getAllStates() {
    this._stateProxy.getAll().subscribe((result) => {
      this.governorates = result.items;
      console.log('states', this.governorates);
    });

}

Within my .html file, I have set up two dropdown menus

//first dropdown
 <p-dropdown #governorateDropdown [showClear]="true" [filter]="true" filterBy="name" placeholder="Governorate" [ngModel]="selectedStateId" (onChange)="updateStore($event)" formControlName="governorate" [options]="governorates" optionLabel="name" optionValue="id"></p-dropdown>

//second dropdown

<p-dropdown [options]="tenants" [filter]="true" filterBy="name" name="tenants" [(ngModel)]="selectedTenantId" placeholder="Select Your Nearest Area" optionLabel="name" optionValue="id" [showClear]="true"></p-dropdown>

Currently, I'm stuck on how to filter store values (tenant id) based on the selected location (state id) in the following function

updateStore(event : any) {
if (this.selectedStateId == 12) {
  this.tenants.filter((value) => value.id == event.value)
}

}

Answer №1

It's important to prioritize the value of tenants over just filtering:

updateStore(event : any) {
if (this.selectedStateId == 12) {
  this.tenants = this.tenants.filter((value) => value.id == event.value)
  }
}

However, it is advisable to keep a separate copy of the array to avoid overriding the existing one:

getAllTenants() { this._tenantService.getTenantsForPublic(undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,999,undefined).subscribe((data) => {
  this.tenants = data.items.filter((item) => item.isActive);
  this.tenantsDB = [...this.tenants];
})

This allows you to filter without affecting the original array:

updateStore(event : any) {
if (this.selectedStateId == 12) {
  this.tenants = this.tenantsDB.filter((value) => value.id == event.value)
  }
}

The dropdown options will now be based on tenantsDB:

<p-dropdown [options]="tenantsDB" [filter]="true" filterBy="name" name="tenants" [(ngModel)]="selectedTenantId" placeholder="Select Your Nearest Area" optionLabel="name" optionValue="id" [showClear]="true"></p-dropdown>

Check out the working example on stackblitz

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

Tips for resolving the issue: Encountered an unexpected token < when parsing JSON data at position 0 using the JSON.parse function

I encountered an error when working on the code mentioned in this post. After removing .json() from response.json() in my code snippet below, the error message changed: return this.http.post('http://localhost:3000/sign-up', body, {headers: head ...

Is it possible to manage the form submission in React after being redirected by the server, along with receiving data

After the React front-end submits a form with a POST request to the backend, the server responds with a JSON object that contains HTML instead of redirecting as expected. How can I properly redirect the user to the page received from the server? For inst ...

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

How to close a Kendo Angular Dialog by clicking a button in a child component

I have a form component that is embedded in a dialog using the kendo dialog service. I am successfully able to call my service and save my form data on the save click event. However, I am currently facing an issue with figuring out how to close the dialog ...

Angular CLI integrated with Isotope version 2

I am facing difficulties when using the isotope-layout module with Angular CLI. To install the module, I used the command: npm install isotope-layout --save After installation, I added the script in my .angular-cli.json file: "scripts": [ ... " ...

The editor is locked and choices are displayed in a vertical orientation

I'm currently experimenting with using draft js in my project to create a wysiwyg editor. However, I've encountered an issue where the editor appears vertically instead of horizontally when I load the component. Any idea why this might be happen ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Leveraging Angular transclusion with a combination of multiple components

I have a parent component with three child components arranged in the following hierarchy: <parent-component> <wrapper-layer> <inner-most> </inner-most> </wrapper-layer> </parent-component> I am unsure of how ...

Discovering the true rendering elements in karma tests: A guide

Recently, I started working on a new project in Angular14. However, when I completed writing the unit tests, all I could see was a series of successful text information and not any HTML elements displayed. How can I view the HTML elements? ...

Generating an XML document using Angular2 and TypeScript

Looking to generate an XML document within an angularjs + Typescript setup. I came across information on using XMLWriter(), however, I'm encountering a "Cannot find name XMLWriter" error. Any recommendations for an alternative method to create an XML ...

Angular 10 encounters difficulties when attempting to execute HttpClient

I encountered an error when attempting to execute "ng build". The error message states: ERROR in node_modules/@angular/common/http/http.d.ts:81:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class. ...

Angular configuration for intercepting HTTP errors with RxJS Replay Subject

I am currently facing an issue where I am trying to retrieve the value of an error and show a customized error message using an HTML element. In order to manage the state of the error, I am utilizing a Replay Subject in my Interceptor. The interceptor is c ...

Transferring dynamic data to an Angular component's controller

Here's what I currently have: <div *ngFor="let career of careers"> <label>{{career.name}}</label> <input type="checkbox" attr.id="{{career.id}}" (change)="doSomethingWithId($event.target)" </div> This is the TypeSc ...

Error when sending Angular 4 GET request with multiple Headers results in a 400 bad request code

I've been attempting to perform a POST request with headers in order to receive a response. The Angular code snippet I'm currently using for this request is shown below: const headers = new HttpHeaders({ 'Content-Type': 't ...

The expected input should be either an HTMLElement or an SVGElement, but the received input is currently null

Below is the code for a component: function SignUpPage() { return ( <> <h1>Sign Up</h1> <input name="userName" /> </> ); } export default SignUpPage; Testing the component: it("should c ...

What is the proper way to add an object to an array within an object in TypeScript?

import {Schedule} from './schedule.model'; export class ScheduleService{ private schedules:Schedule[]=[ new Schedule("5:00","reading"), new Schedule("6:00","writing"), new Schedule("7:00","cleaning") ]; getSchedule(){ ret ...

Accessing the access token in your Angular application right after the login process with Auth0

I've been working on integrating auth0-spa-js in my Angular application, and I'm encountering an issue extracting the access token after a successful user authentication. Despite reading multiple articles on the topic, I'm still unclear on h ...

Display a JSON file within an Angular application using HTML

I have a JSON (link to the JSON) that I want to display in an html file. JSON: { "recipes": { "FRYING": { "Anchovies": [ [ {"500": "thawing"} ], [ {"60": "nothing"} ] ], "Codfis ...

Using a decorator with an abstract method

Discussing a specific class: export abstract class CanDeactivateComponent { abstract canLeavePage(): boolean; abstract onPageLeave(): void; @someDecorator abstract canDeactivateBeforeUnload(): boolean; } An error occurred stating that A decorat ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...