Building a dynamic list of select elements using Angular: A step-by-step guide

Upon signing up for my Angular application, users are required to set up their accounts by adding instruments to their profile.

An instrument is defined by the following interface:

export interface Instrument {
    id: string;
    name: string;
    groupId: string;
}

The concept involves having a list of dropdown menus, initially starting with just one dropdown. Below each dropdown, there is a button that, when clicked, adds an empty dropdown field. I have successfully implemented this functionality in my code. However, I encountered an issue where selecting an instrument in the first dropdown and then adding another dropdown results in the option in the first dropdown being reset, giving the appearance that nothing is selected (even though the array remains unchanged except for the new empty value).

Here is the code snippet:

HTML

<div 
    *ngFor="let userInstrument of userInstruments; let id = index"
>
    <mat-form-field appearance="fill" fxFlex>
        <mat-label>Instrument</mat-label>
        <mat-select placeholder="Guitar" [(ngModel)]="userInstruments[id]" name="item">
            <mat-option value="">
                None
            </mat-option>
            <mat-option [value]="instrument.id" *ngFor="let instrument of instruments">
                {{instrument.name}}
            </mat-option>
        </mat-select>
    </mat-form-field>
</div>
<p id="add-instrument" (click)="addInstrument()">
    Add another instrument?
</p>

Typescript


  userInstruments: string[] = [];
  instruments: Instrument[] = [];

  constructor(private utilsDataService: UtilsDataService) {
    this.utilsDataService.loadInstruments();

    this.utilsDataService.getInstruments$()
      .pipe(
        takeUntil(this.destroyed$)
      ).subscribe(i => {
        if (!!i) {
          this.instruments = i;
        }
      })
  }

  ngOnInit(): void {
  }

  addInstrument() {
    if (this.addInstrumentValid()) {
      this.userInstruments.push("");
    }
  }

Answer №1

After some research, I discovered that ngModel is on its way to being phased out. Upon visiting the Angular Material page, I noticed they recommended using [(value)]="binding" instead of `[(ngModel)]=binding" for the select element. Implementing this change resolved the issue I was facing. Much appreciated!

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

How can you efficiently enable Angular 4 routing on a production server?

It took me a dedicated 6 days to transition an HTML5-only app into an Angular 4 routing application, all in the hopes of enhancing its SEO capabilities. However, upon deployment, I discovered that direct URLs were resulting in frustrating 404 pages. For e ...

Astro component experiencing script tag malfunction within content collection

I'm trying to create something using a script tag, but for some reason the script doesn't seem to be working properly. Below is my content collection: --- title: Essay Similarity stakeholder: THESIS articleDate: 05 Feb 2023 projectStart: 2022-08 ...

Interactions with the browser are ineffective in headless mode on Chrome

When it comes to Angular test automation, I rely on various mouse and keyboard actions such as mouseDown, Key.ENTER, and Key.ARROW_DOWN within my it block. These actions work flawlessly in a regular browser. However, the same test case fails when executed ...

Why doesn't TypeScript perform type checking on a two-dimensional array?

Here's a simple code snippet I've been using to create a 2D array: type cell = { id: string; }; const board: cell[][]; board = Array(10) .fill("") .map((x) => Array(10).fill(ANY TYPE CAN GO HERE WHY?)); Oddly enough, when I popu ...

Angular Form Container

I am in the process of creating a wrapper for forms. Everything is functioning except for the validation aspect. The issue lies in the fact that my ngForm property does not include the controls from the ng-content. My objective is to have the ngSubmit Even ...

Angular: Validation triggered following ngModelChange event

I am dealing with an input field that has a customValidator called fooValidator. This custom validator checks if the input matches a specific regular expression: <form #contratForm="ngForm"> <input type="text" ...

"Encountering an 'Access-Control-Allow-Origin' error in the VSCode Debug Console, even though the network tab in Chrome DevTools displays a 200OK

In my Angular 7 project, I encountered an issue while using HttpClient. When I click a button, the following code snippet is executed: this.http .get('http://localhost:30123/api/identity/name/' + this.name) .subscribe((answer: Identit ...

How is it possible that this does not trigger a compile error? (Mongoose, Typescript, MongoDB)

I am in the process of setting up a MERN project in Typescript and I have come across something that puzzles me. Despite my expectations, there is no compilation error in TS with the following code: Here's the model snippet: import { Document, Schema ...

How can I connect one input field to another in Angular 2, but only if the first field is in its original pristine state

There are two input fields available: <input type="text" [(ngModel)]="title" name="title"> <input type="text" [(ngModel)]="og_title" name="og_title" value="{{ title }}"> I aim to have the og_title field match the title field until og_title is ...

I am encountering issues with running my tests using react-testing-library alongside TypeScript

Currently facing issues with react-testing-library in my TypeScript-based React project. Despite researching and following various tutorials, I am unable to resolve the problem. I have experimented with changing configurations in babel.config.js, tsconfig ...

Guide on setting up p-menubar in PrimeNG to expand in the opposite direction, from left to right, for the responsive

How can I modify the CSS styles or configure the p-menubar from PrimeNg to have it expand from right to left in the responsive version? Currently, when using the classes align-items-center flex justify-content-between, the menu remains stuck to the right e ...

Is there a disparity in capabilities or drawbacks between ViewChild and Input/Output in Angular?

As I delve into Angular ViewChild and compare it to Input/Output parameters, I can't help but wonder if ViewChild has any drawbacks or limitations compared to Input/Output. It appears that ViewChild is the preferred method, as all parameters are now ...

Using Angular 8 to Toggle Switches with Data Binding

Creating a toggle switch similar to this image is my current task https://i.sstatic.net/8oTmi.png While attempting to bind the data to the switch using [checked], like shown below, <div class="mb-3"> <div class="d-flex mb-2"> ...

Having trouble displaying child nodes in MatTreeView with Angular 14?

In an Angular project, I am attempting to display a private group's data from GitLab (utilizing a public one for testing purposes). To achieve this, I have implemented the NestedTreeView component. While the parent nodes are displaying correctly, I am ...

Guide to connecting a table to a detailed view in Angular

I've implemented a table in Angular that fetches data from a web api and displays it. My goal is to link the first column, which contains the (sys_id) ID number, to a detailed view of that specific ID. To achieve this, I know I need to make a GET req ...

Integrate a fresh global JSX attribute into your React project without the need for @types in node_modules

It is crucial not to mention anything in tsconfig.json. Error Type '{ test: string; }' cannot be assigned to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'. Property 'test' does not exi ...

I am facing issues with Angular's @ContentChild and unable to make it work

Having some trouble grasping the concepts of Angular2, specifically with the @ContentChild feature not working as expected. I must be making a simple mistake somewhere, but I just can't seem to find it. Any assistance would be greatly appreciated. ap ...

What is the most efficient method for scheduling a task X hours following the commencement of an event?

We have a platform where users can upload content. There is a requirement to trigger a specific task exactly N hours after each piece of content is uploaded. I am curious about the most efficient method for scheduling jobs based on these types of events? ...

Angular component fails to display

Below is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['../assets/css/app.component.css'] }) export class Main ...

Error Detected: An unhandled error occurred, triggering a promise rejection: TypeError: The super expression must be either null or a function in Angular version 6

Upon deploying the application on AWS Elastic Beanstalk, an error has surfaced. While the build and deployment processes were successful, one module is giving a Super Expression error. The other modules are functioning correctly, and everything works fine ...