In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement:

In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their values from APIs and utilize two-way binding.

For example, if the first dropdown contains student names and I select a different option, I want the second dropdown (which lists classes like 1st Grade, 2nd Grade, etc.) to automatically select the corresponding class for that student. So, if I choose the student 'John' who is studying in 2nd grade, the second dropdown should show '2nd Grade' as selected.

My Attempt so far:

I've used the (change) event in the first select option to retrieve the necessary value for the second dropdown. However, I'm unsure how to assign this value to the second dropdown.

1st Dropdown:

<select
        class="form-control form-control-lg form-control-solid"
        name="studentId"
        [(ngModel)]="model.studentId"
        required
        #studentId="ngModel"
        (change)="getClassByStudent(studentId.value)"
      >
        <option
          *ngFor="let student of studentList"
          value="{{ student .id }}"
        >
          {{ student.studentName}}
        </option>
      </select>

2nd Dropdown:

<select
        class="form-control form-control-lg form-control-solid"
        name="classId"
        [(ngModel)]="model.classId"
        required
        #classId="ngModel"
      >
        <option
          *ngFor="let class of classList"
          value="{{ class.id }}"
        >
          {{ class.className }}
        </option>
      </select>

TypeScript:

 getClassByStudent(studentId) {
      debugger;
      this.commonService.API_URL = 
      `${environment.apiUrl}/admin/studentClass/${studentId}`;
       this.commonService.getList().subscribe(
       response => {
          this.classAsPerStudent = response?.data;
          this.classId= this.classAsPerStudent.studentId
     });
 }

Answer №1

There seems to be crucial information missing in the question, but I've attempted to recreate the scenario and resolve the issue.

If we assume that the getList method within your CommonService returns data like this:

{
  "data": {
    "studentId": 5
  }
}

Make sure to assign it to this.model.classId instead of this.classId inside the subscribe block.

getClassByStudent(studentId) {
  // ...
  this.commonService.getList().subscribe((response: any) => {
    this.classAsPerStudent = response.data;
    this.model.classId = this.classAsPerStudent.studentId; // <----- HERE
  });
}

Another important detail is that the values of all options in the second select list should be class.id instead of coaches.id:

<select
  class="form-control form-control-lg form-control-solid"
  name="classId"
  [(ngModel)]="model.classId"
  required
  #classId="ngModel"
>
  <option
    *ngFor="let class of classList"
    [value]="class.id"
  >
    {{ class.className }}
  </option>
</select>

Here's a Live Code Sample on StackBlitz for reference.

NOTE: Selecting any student from the first list will automatically update the option in the second select list to show Class 5. This constant change to Class 5 is due to my hardcoded studentId as 5 in the example.

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

Angular2: Is unsubscribing from host listeners necessary? How do host listeners function? If I don't need to unsubscribe, under what circumstances are they automatically unsubscribed?

@HostListener('window:scroll', ['$event']) onScroll(event) { // Handling scroll event } I have implemented a 'onScroll' function to listen for scroll events in various components. I haven't included an unsubscrib ...

The double curly brackets in Angular for text interpolation are failing to work, causing the variable values to not be shown on display

I'm having trouble getting the details of a student to display on my app. Here's the code: import { Component, OnInit } from '@angular/core'; import { Student } from '../student'; import { ActivatedRoute } from '@angular/ ...

I am having trouble getting the guide for setting up a NextJS app with Typescript to function properly

For some time now, I have been experimenting with integrating Typescript into my NextJS projects. Initially, I believed that getting started with Typescript would be the most challenging part, but it turns out that installing it is proving to be even more ...

The TypeScript error occurs when attempting to assign a type of 'Promise<void | Object>' to a type of 'Promise<Object>' within a Promise.then() function

I'm currently working on a service to cache documents in base64 format. The idea is to first check sessionStorage for the document, and if it's not there, fetch it from IRequestService and then store it in sessionStorage. However, I've encou ...

Allowing the OPTIONS method in CORS when sending a REST request from AJAX to a WCF Service

After spending 7 hours scratching my head, I am still unable to figure this out. Despite my extensive search on the web, no luck has come my way. My Angular App is sending requests to a WCF command-line hosted service application. To bypass CORS, I utilize ...

Angular allows for the use of the ngIf condition within nested loops to control the display of

I'm currently working on implementing a navigation side menu using Angular with 3 levels of submenus. Below is the code I have tried: <ul class="nav metismenu" id="side-menu" *ngIf="menulist.length != 0"> <li *ngFor="let menu1 of menuli ...

What does the concept of "signaling intent" truly signify in relation to TypeScript's read-only properties?

Currently diving into the chapter on objects in the TypeScript Handbook. The handbook highlights the significance of managing expectations when using the readonly properties. Here's a key excerpt: It’s crucial to clarify what readonly truly signif ...

What could be causing this error for my NPM module in a .NET Core project using Typescript?

My Typescript configuration seems to be causing some issues, even though everything works fine without TS. Could the problem lie in my .d.ts file? And do I really need it for webpack? I have a basic NPM module: index.js: var MyMathTS = function(a, b){ ...

Filtering in RxJS pipelines can be compared to an if-else statement

I'm not very familiar with JS and RxJS, so please pardon me if my question seems trivial. Here is a code snippet that I didn't write: prepare(): Observable<any> { const i = of({}).pipe( // Check if file type is image fil ...

Compiling Typescript with module imports

In my project, I am working with two files named a.ts and b.ts. The interesting part is that file b exports something for file a to use. While the TypeScript compiler handles this setup perfectly, it fails to generate valid output for a browser environment ...

Having difficulty forming queries correctly using TypeScript, React, and GraphQL

Apologies for the potentially naive question, but I am new to working with GraphQL and React. I am attempting to create a component that contains a GraphQL query and incoming props. The props consist of a query that should be passed into the GraphQL query. ...

How come the value assigned to the [(ngModel)] variable does not show up as the selected value in the PrimeNG drop-down menu?

When passing data from the parent to child component, the normal text input is populated with the data received from the parent, but the same does not work with dropdowns. The code block where data is passed to the variable enteredName functions as intend ...

Looking up the Vue.js type definitions in TypeScript

I'm currently working on enabling type checking in my Vue.js code (v2.2.1). My initial goal is to ensure that this specific line compiles with TypeScript (meaning I want the Vue class to be properly identified): var app = new Vue(); I've discov ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Refreshing the browser causes Angular route to display raw JSON data

I have been working on a MEAN stack application and I have set up a proxy configuration for development purposes. Everything seems to be in order as I am able to successfully call an API from Angular/Node. However, the issue arises when I refresh the brows ...

The installation of the module assets-webpack-plugin was not completed through the npm install command

When trying to install assets-webpack-plugin from https://github.com/ansrivas/angular2-flask by running npm install within the front/ folder, I encountered an issue where the plugin was not being added to node-modules/ as expected. Strangely enough, when ...

Terminal displays Typescript variable syntax error

Recently, I've been delving into TypeScript using Visual Studio Code. However, I've encountered a perplexing syntax error that stems from how I've defined a variable. Here's an example of my declaration: let year:number = 2015 My term ...

Enhancing Angular2 Routing with Angular4 UrlSerializer for Seamless HATEOAS Link Integration

As a newcomer to Angular4, I am currently exploring how to consume a HATEOAS API. My goal is to either pass an object that contains the self reference or the self reference link itself through the routing mechanism (for example, by clicking on an edit link ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data. const handleSubmit = async (event: any) => { event.preventDefa ...