Steps to dynamically populate dropdown menus based on the selected options from other dropdown menus

I am working on a project that involves two dropdown menus. The options for the first dropdown menu are stored in a file called constant.ts. Depending on the selection made in the first dropdown, the options for the second dropdown will change accordingly.

.constant.ts

export const ActionRecordConstant = {
  contact: 'Contact1',

  about: 'About',
};

.component.ts

public getCodes() {
  let baseUrl = `/api end point`;
  this._restfulService
    .restfulGetData(baseUrl)

    .subscribe(
      (actionLookupData: ActionLookupData) => {
        if (actionLookupData) {
          this.contactCodes = actionLookupData.contactCodes;
          this.aboutCodes = actionLookupData.aboutCodes;
        }
      },
      (err) => {
        console.error(err);
      },
    );
}

public contactSelect(data: any) {
  this.contactId = data;
}
public aboutSelect(data: any) {
  this.aboutId = data;
}

.component.html

<div class="row mt-15">
  <div class="form-group">
    <div class="col-sm-3">
      <label> <b>Contact</b></label>
    </div>
    <div class="col-sm-7">
      <select class="form-control">
        <option value="" disabled [selected]="true"></option>
        <option>About</option>
        <option>Contact</option>
      </select>
    </div>
  </div>
</div>
<div class="row mt-15">
  <div class="form-group">
    <div class="col-sm-3">
      <label> <b>Action</b></label>
    </div>
    <div class="col-sm-7">
      <select>
        <option value="" disabled [selected]="true"></option>
        <option>//code</option>
      </select>
    </div>
  </div>
</div>

I need to implement functionality where selecting an option from the first dropdown will dynamically populate the options in the second dropdown based on the selection made.

Answer №1

If you want to take action with a subject and assign specific values for dropdowns, you can use switch case statements.

<select
  *ngIf="billingActions$ | async as actions"
  #action
  (change)="onSelectAction(action.value)"
>
  <option value="0" selected>Choose an action</option>
  <option *ngFor="let action of actions" [value]="action.name">
    {{ action.name }}
  </option>
</select>
<select *ngIf="actionCodes$ | async as codes">
  <option *ngFor="let code of codes">{{ code.name }}</option>
</select>

When an action is selected, the respective codes will be assigned.

 private selectedAction = new Subject();
  private selectedAction$ = this.selectedAction.asObservable();

  // Define different types of actions
  billingActions = [
    {
      name: 'billing',
    },
    {
      name: 'member',
    },
    {
      name: 'other',
    },
  ];

  // Define corresponding codes for each type of action
  memberContactCodes = [
    {
      name: 'member Action Code A',
    },
    {
      name: 'member Action Code B',
    },
  ];

  billingActionCodes = [
    {
      name: 'billing Action A',
    },
    {
      name: 'billing Action B',
    },
  ];

  otherActionCode = [
    {
      name: 'Other Action A',
    },
    {
      name: 'OtherAction B',
    },
  ];

  categories = [
    { id: 1, name: 'billing' },
    { id: 2, name: 'others' },
  ];

  billingActions$ = of(this.billingActions);

  // Map the selected action to its respective codes
  actionCodes$ = this.selectedAction$.pipe(
    map((action: string) => {
      switch (action) {
        case 'billing':
          console.log('billin');
          return this.billingActionCodes;
        case 'member':
          return this.memberContactCodes;
        case 'other':
          return this.otherActionCode;
        default:
          return this.billingActionCodes;
      }
    })
  );

  onSelectAction(value) {
    this.selectedAction.next(value);
  }

You can test this functionality using the following example: https://stackblitz.com/edit/angular-ivy-5ea4fw

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

Select a color at random from the array, animate it, then repeat the process by selecting a new random color from the

Currently, I am utilizing gsap and three js to animate a light source. I have an array containing various colors that I would like to cycle through randomly during the animation process. My objective is to continuously loop through the random color selec ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Deactivate numerous buttons with the help of jQuery

Within my MVC view, I have a Razor foreach loop that generates table rows with buttons: @foreach (var item in Model) { <tr> <td>@item.Id</td> <td> <button id="btn" class="button btn-primary" type= ...

Storing blank information into a Mongodb database with Node.js and HTML

Can someone please assist me with solving this problem? const express=require("express"); const app=express(); const bodyparser=require("body-parser"); const cors=require("cors"); const mongoose=require("mongoose"); ...

What could be causing my mongoose array to remain empty without any values being stored in it?

Issue at Hand While I have come across several similar problems on Stack Overflow about this particular issue, none of the solutions provided seemed to work for me. I am in the process of developing a basic Forum application with two routes - one for cre ...

Sending Node.js array from endpoint to Javascript function

I am facing an issue with my HTML chart that is supposed to display an array from a JavaScript function called 'window.testDataArray'. Instead of using a sample array, I want to fetch the array data from a server endpoint. However, I am unsure ab ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

What is the reason that Ionic Lifecycle hooks (such as ionViewWillEnter and ionViewWillLeave) do not trigger when utilized as an HTML Selector?

I have a project using Angular along with Ionic 4. I encountered an issue where the Ionic Lifecycle Hooks in the child page do not fire when it is called from the parent page's HTML using the HTML Selector. Why does this happen? How can I properly ut ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

Successfully received response from Ajax post - unable to display on screen

After successfully posting data to the server using $.post(), I am encountering issues when trying to work with the response. Unfortunately, nothing appears - no console log is shown and I am unable to replace text or HTML with the retrieved data. Below i ...

Could Ramda assist in enhancing pipeline/composition processes with a logging feature?

Considering implementing logging within a composed chain of functions, the following code demonstrates how it can be achieved: const f = R.compose( transformation2, doAlso(x => console.log(`id: ${x.id}`)), transformation1 ) This approach would c ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Tips for automatically scrolling the Google Maps view in a React application

After implementing the google-map-react package, I have designed a TypeScript MapView component with the following code snippet. export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element { const [mapZoom, setMapZo ...

A guide on determining the number of rows in an ag-grid with TypeScript and Protractor

I am currently working on extracting the number of rows in an ag-grid. The table is structured as follows: <div class="ag-body-container" role="presentation" style="height: 500px; top: 0px; width: 1091px;"> <div role="row" row-index="0" row-id="0 ...

Convenient Method for Making POST Requests with the Node Request Module and Callback

Does the .post() convenience method in Javascript/Node's request module accept a callback? I'm confused why it would be throwing an error like this: var request = require('request'); request.post({url: 'https://identity.api.foo/v ...

When a text is wrapped by an HTML div using absolute positioning, is there a way to prevent it from wrapping without relying on white space

I have a group of div elements positioned absolutely on the screen. If any div contains content that is too big for the screen, the browser wraps it into multiple lines to fit. However, I do not want this behavior. Instead, I want the overflowing content ...

Tap the <li> element in a select2 dropdown from Bootstrap using internjs

I am currently encountering an issue while trying to select values from a Bootstrap-select2 drop-down in my form during the process of writing some function tests. If Select2 is unfamiliar to you, here are some examples that may help: The drop-downs are ...