Angular: ngModelChange not updating value in dropdown menu

I have successfully implemented a dropdown feature like this:

    <select (ngModelChange)="onChange($event)">
        <option *ngFor="let quantity of quantities" [ngValue]="quantity">
          {{ quantity }}
        </option>
    </select>

The component code is presented below:

export class ProductItemComponent implements OnInit {
    @Input()
    productItem: Product;

    @Output()
    addProduct: EventEmitter<Product> = new EventEmitter();

    @Output()
    selectedQuantity: EventEmitter<Number> = new EventEmitter();

    quantities: number[] = [];

    constructor(private productService: ProductsService) {
        this.productItem = {
            id: 1,
            name: '',
            price: 0.0,
            url: '',
            description: ''
        };

        this.quantities = Array.from({ length: 30 }, (_, i) => i + 1);
    }

    ngOnInit(): void {}

    addToCart(p: Product): void {
        this.addProduct.emit(p);
    }

    public onChange(event: any): void {

         const quantity = event.target.value;

         console.log('\n');
         console.log('quantity ' + quantity);
         console.log('\n');

        this.selectedQuantity.emit(quantity);
    }

    showProductDetails(product: Product): void {
        this.productService.setCurrentProduct(product);
    }
}

However, there is an issue where the quantity value is not updating when changed in the dropdown. How can I address this problem?

Edit:

I have found that changing ngModelChange to change in the <selector> tag resolves the issue:

<select (change)="onChange($event)">
        <option *ngFor="let quantity of quantities" [ngValue]="quantity">
          {{ quantity }}
        </option>
    </select>

While this workaround works, I am curious as to why ngModelChange does not function as expected.

Answer №1

In order for the functionality of ngModel to be operational, it is necessary for the input to be equipped with a name attribute. (Error messages will likely appear in the console if this is not done)

If the dropdown does not have any variable attached to enable two-way binding, then there is no benefit in utilizing ngModel or ngModelChange.

Instead, opt for a simple (change) event:

(change)="onChange($event)

Answer №2

For proper use of ngModelChange, it is essential to have ngModel in place where it is supposed to be.

change refers to the regular change detection of DOM elements in Angular, such as input fields, dropdowns, and radio inputs.

To gain a better understanding of this concept, refer to the following resources:

Answer №3

Implement the use of (ngModelChange) alongside [(ngModel)] as shown below:

<select [(ngModel)]="selectedValue" (ngModelChange)="onChange($event)">
 <option *ngFor="let quantity of quantities" [ngValue]="quantity">
      {{ quantity }}
 </option>
</select>

This configuration ensures that onChange($event) is triggered after the update of selectedValue through [(ngModel)]. The (ngModelChange) event is emitted by [(ngModel)] after updating the model.

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

Obtaining a bearer token from Auth0 in an Angular application involves a few

Can someone guide me on obtaining the Auth0 bearer token in Angular when using the Auth0 SDK and AuthModule? @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public auth: AuthService) {} intercept(request: HttpRequ ...

Expired URL in Ionic 3 Navigation

I'm a novice at using Ionic. I recently started my first project about a month ago and it's nearing completion. However, I noticed that whenever I run ionic serve, my app always defaults to localhost:8100. For example, when I land on the home pa ...

Generating a fresh instance of a class that mirrors an already existing instance, all without relying on eval()

I have an object named uniqueObject of an unspecified class and I am in need of creating a duplicate object from the same class. Here's my current approach: I extract the class name using uniqueObject.constructor.name. Then, I generate a new object o ...

Learn the proper way to write onClick in tsx with Vue 2.7.13

current version of vue is 2.7.13 Although it supports jsx, I encounter a type error when using onClick event handling. The type '(event: MouseEvent) => Promise<void>' cannot be assigned to type 'MouseEvent' Is there a correct ...

Exploring deep within the layers to reach a component in Angular

In the hierarchy of components, I have a parent component that contains multiple other components. Among these nested components, there is a special component that I am particularly interested in. ParentComponent SubComponent1 MySpecialCom ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

"Encountered a problem with Next JS API while trying to fetch data from the app directory

import { NextResponse } from "next/server"; export async function POST(request: Request) { const data = await request.json(); console.log(data); return NextResponse.json({ foo: "boo" }); } next version = "next": &quo ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

AutoAnimate animation customization is not compatible with React

I'm in the process of integrating a plugin from this source into my code. I've made adjustments to it for React, but it's still not working as expected. Can you assist me with resolving this issue? Custom Hook: import { useRef, useLayoutEff ...

Encountering TypeScript error TS2345 while attempting to reject a Promise with an error

I recently encountered a perplexing TypeScript error message that I am struggling to comprehend. The specific error reads as follows: error TS2345: Argument of type '(error: Error) => void | Promise' is not assignable to parameter of type & ...

Encountering a problem: array property length not found in Angular application?

I am trying to create a list of superheroes by looping through an array, but I keep encountering an error stating that the property length is missing from the array. (please refer to the screenshot) Here is my code in app.component.ts import { Component ...

Facing difficulties in Angular 8 while trying to import firestore and firebase for an authentication system

While attempting to implement Firestore/Firebase functionalities for Google OAuth signin, I encountered an error indicating that Firebase is not imported: https://i.sstatic.net/oL4rY.png CODE: ERROR in node_modules/@angular/fire/auth/auth.d.ts:4:28 - er ...

Encountering an error while trying to update an Angular application to version 10

I am currently running a demo app and I am new to Angular. Below is my category list component. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; im ...

What steps should I take to plan a collaborative code-sharing project?

As I develop various applications utilizing a core framework of my own creation, I am looking for a way to easily manage updates across all these applications. I have structured the code by creating a GitHub project where the main branch consists of the co ...

What is the best way to retrieve the value of the selected mat-option?

I've been struggling to extract the selected value of a mat-option using this specific HTML and TypeScript code. html <mat-form-field appearance="outline" floatLabel="always"> <mat-label>TRA Type</mat-label> ...

Acquiring and resetting Angular states: A beginner's guide

I'm facing a situation where I need to perform a route jump (essentially a refresh) on the same page, but this jump includes state data. However, even though the state contains valuable information, I am only able to access it through history and cann ...

Using Firebase with Angular 4 to fetch data from the database and show it in the browser

Currently diving into Angular 4 and utilizing Firebase database, but feeling a bit lost on how to showcase objects on my application's browser. I'm looking to extract user data and present it beautifully for the end-user. import { Component, OnI ...

Can discriminated unions solely be utilized with literal types?

When looking at the code snippet below, I encountered an issue with discriminating the union type using the typeof operator. function f(arg: { status: number; one: boolean } | { status: string; two: boolean }) { if (typeof arg.status === "number&q ...

Is it possible to customize webpack 4 modules in order to enable Jasmine to spy on their properties?

I've been facing issues trying to run my Jasmine test suite with webpack 4. Ever since I upgraded webpack, I keep getting this error message in almost every test: Error: <spyOn> : getField is not declared writable or has no setter The problem ...

Unraveling NGRX: a guide to invoking factory selectors from within additional selectors

NGRX has deprecated selectors with props in version 11. The recommended method now is to create factory selectors. How can you nest selectors or call one from another and pass the state between them? Prior to the change, if we had the following two selec ...