Utilize Angular Typscript to bind and select options dynamically

When I require two select options in a lab setting: First select: Iced drink, Hot drink. If I choose iced drink, the second select will show Black tea, green tea, coffee. If I choose hot drink, the second select will display Milk, Chocolate milk. How can I update the selectable items in the second option based on the choice made in the first option?

This is my current code:

<mat-form-field appearance="fill">
            <mat-label>Select Table</mat-label>
            <mat-select [(ngModel)]="selectshowedOption" (ngModelChange)="getselectedtableOption($event)" name="type">
              <mat-option *ngFor="let table of options" [value]="table.name">
                {{table.name}}
              </mat-option>
            </mat-select>
          </mat-form-field>


options = [
    { name: "ICE Drink", value: 1 },
    { name: "HOT Drink", value: 2 }
  ]

Answer №1

One convenient method is to create two separate "seconds" select elements and use them accordingly.

<mat-select *ngIf="selectshowedOption==1" [(ngModel)]="drink">
   ...
</mat-select> 
<mat-select *ngIf="selectshowedOption==2" [(ngModel)]="drink">
   ...
</mat-select> 

Alternatively, you can define a new variable:

hotDrinks=[....]
coldDrinks=[....]
secondTable:any=this.hotDrinks //initialize with hotDrinks

Then, iterate over secondTable and update the variable in your select drop-down:

<mat-select [ngModel]="selectshowedOption" 
            (ngModelChange)="selectshowedOption=$event;
                             secondTable=$event==1?hotDrinks:coldDrinks">
...
</mat-select>

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

Oops! Looks like there was an error trying to assign the value "$event" to the template variable "element". Remember, template variables can only be read

Can anyone assist me in identifying the issue with this code? <div *ngFor="let element of list; let index=index"> <mat-form-field> <input matInput type="string" [(ngModel)]="element" name="element ...

Angular: A guide to managing Observables in a service with changing routes

Within my Angular application, I have a MealsModule that contains SharedModule. Inside the SharedModule, there is a MealsService in the providers section which utilizes Firebase as the database. Below is the content of my SharedModules: import {ModuleWit ...

Tips for preventing flickering caused by set Interval in angular 2+

Displaying dynamic latitude and longitude data on Google Maps while using setInterval() function. Code snippet below: this.timer = setInterval(()=>{this.getMapData();},30000); An issue arises where the map flickers when updating the data with this.get ...

TS2304 TypeScript (TS) Unable to locate the specified name

Encountering an error message stating Cannot find name 'Record'. Do I need to install a specific package for this class? Severity Code Description File Project Line Suppression State Error TS2304 (TS) Cannot find name 'Record ...

Typescript tip: Changing the property type in a discriminated union

I'm encountering a slight issue with TypeScript inference on discriminated unions. Let's say I have the following types: type TypeA = { type: 'a'; formData: number; onSubmit: (data: number) => void; }; type TypeB = { type: & ...

The function of edit does not exist

I'm currently working on creating a discord bot that will send a message to a specific channel upon startup. Initially, I was able to send the message to the designated channel without any issues. However, when I attempted to edit the message, an erro ...

Blurry text issue observed on certain mobile devices with Next.js components

There continues to be an issue on my NextJS page where some text appears blurry on certain mobile devices, particularly iPhones. This problem is only present on two specific components - both of which are interactive cards that can be flipped to reveal the ...

Unable to locate the 'functions scss error within the Angular application

Having recently created a fresh angular 7 application and incorporating scss, I encountered an error after building the application. The style.scss class contains the following import: @import '../node_modules/bootstrap/scss/bootstrap.scss'; I ...

Exploring Angular's APP_INITIALIZER: Comparing Promises and Observables

I have implemented an Angular v4 application where I need to retrieve settings from the server before the app starts. This is achieved using the APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: initializeSettings, deps: [SettingsService], ...

Angular version 5 consistently replaces the chosen date with the current date

Currently facing an issue with an input field that contains a date. Whenever a date is selected that is not today's date, it always defaults to the current date and gets saved in the backend. I need the selected date to be saved instead. The console l ...

Is there a way to access the state value within the reducer function of createSlice?

Currently, I am utilizing redux-toolkit within my react project. A concern arises in a specific reducer inside the createSlice method where I aim to incorporate an existing array of entities from the state and then merge it with a new array before finalizi ...

Utilizing a single route guard for multiple routes with varying authorization requirements

In my Angular 6 project, I currently have an canActivate AuthGuard that is set up to load ComponentA. Now, I am wondering if it's possible to reuse the same AuthGuard for Component B, even though the authorization logic for Component B is completely ...

"Is it possible in Typescript to set the parameters of a returning function as required or optional depending on the parameters of the current

I am currently exploring Typescript and attempting to replicate the functionality of styled-components on a smaller scale. Specifically, I want to make children required if the user passes in 'true' for the children parameter in createStyledCompo ...

What is the best way to employ the pick function with optional types within nested TypeScript structures?

I am interested in learning TypeScript. dynamicContent?: { data?: { attributes?: { baccarat?: { title?: string | null; content?: string | null } | null; baccaratOnline?: { title?: string | null; content?: string | null } | null; ...

Assistance required for setting a value in a mat-select using Angular

Could really use some assistance resolving the issue with mat-select I'm aiming to establish the initial values by utilizing the following code snippet: orders: Order[] = [{"dish":"steak-0"},{"dish":"tacos-2" ...

Tips for Ensuring the Observable Completes Before Subscribing

I utilized RXJS operators in my code to retrieve an array of locations. Here is the code snippet: return O$ = this.db.list(`UserPlaces/${this.authData.auth.auth.currentUser.uid}`, { query: { orderByChild: 'deleted', equalTo: fal ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

`The Art of Curved Arrows in sigjma.js, typescript, and npm`

I have encountered an issue while trying to draw curved arrows in sigma.js within my TypeScript npm project. The error occurs on the browser/client-side: Uncaught TypeError: Cannot read properties of undefined (reading 'process') at Sigma.pro ...

A versatile component loader that serves as a shared service for resolving components

Utilizing the ComponentFactoryResolver is necessary to dynamically incorporate components. In my scenario, I have a modal window that is loaded dynamically upon clicking a button on the view. The code for this operation appears as follows: let componentFa ...