The value is not being displayed by ngModel

When working with HTML, I encountered an issue where the ngModel was not displaying even though the selectedValueModel was already assigned. I also tried using [ngValue], which resulted in the value being passed as undefined to my ngModelChange function.

Any help would be greatly appreciated.

foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
selectedValueModel = {value: 'steak-0', viewValue: 'Steak'};
@Output() selectedValueChange = new EventEmitter()

changing(newValue: any) {
    this.selectedValueModel = newValue
    this.selectedValueChange.emit(newValue)
  }

Here is my HTML:

<mat-form-field>
    <mat-select placeholder="Favorite food" 
   [(ngModel)]="selectedValueModel.value" 
   (ngModelChange)="changing($event)" name="food">
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>

Answer №1

If you are facing issues with your ngModel not showing the correct value from your model, it is possible that there is another input in your form with the same name.

<form>
    <input [(ngModel)]="selectedItemModel.value" name="food">
    <input [(ngModel)]="anotherModel" name="food">
</form>

Answer №2

Modify as follows:

<mat-form-field>
<mat-select placeholder="Favorite food" 
[(ngModel)]="selectedValueModel"
(ngModelChange)="changing($event)" name="food">
  <mat-option *ngFor="let food of foods" [value]="food.value">
    {{food.viewValue}}
  </mat-option>
</mat-select>

Answer №3

To include the entire object in Angular material, as opposed to standard Angular practice, you will utilize [value] for binding the complete object, rather than [ngValue].

Since we are now binding an entire object instead of a primitive value, we must compare your predefined object with the object in the array. This can be achieved by using Angular's compareWith function. Update your code as follows:

<mat-select placeholder="Favorite food" [(ngModel)]="selectedValueModel" 
  (ngModelChange)="changing($event)" name="food" [compareWith]="compFn">
  <mat-option *ngFor="let food of foods" [value]="food"> <!-- Set food as the value! -->
    {{food.viewValue}}
  </mat-option>
</mat-select>

Next, implement the compFn function:

compFn(c1: Food, c2: Food): boolean {
  return c1 && c2 ? c1.value === c2.value : c1 === c2;
}

Check out this StackBlitz for a live 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

Capture a screenshot with Puppeteer at a random URL stop

I am facing an issue with my service nodejs running on Ubuntu, where I use puppeteer to capture screenshots of pages. However, the method page.screenshot({fullPage: true, type: 'jpeg'}) sometimes fails on random URLs without displaying any errors ...

What is the reason that TypeScript cannot replace a method of the base class with a subtype?

Here's a straightforward example. type Callback<T> = (sender: T) => void; class Warehouse<T> { private callbacks: Callback<T>[]; public constructor(callbacks: Callback<T>[]) { this.callbacks = callbacks; ...

Managing unpredictable fields within a TypeScript interface Let me known if you need further assistance

Currently, I am developing a web application using Angular and encountered an issue with the JSON data returned by a service call. The problem arises when the mapped JSON contains an Object within one of the fields with unpredictable content. How can I han ...

Using the locale identifier en-GB can lead to date formats being displayed incorrectly

I'm struggling with setting up the correct locales in my Angular application. As per the documentation, I've inserted the following code snippet into my angular.json file. "projects": { "appname": { ..., "i18n&q ...

Error message from OpenAI GPT-3 API: "openai.completions function not found"

I encountered an issue while trying to execute the test code from a tutorial on building a chat app with GPT-3, ReactJS, and Next.js. The error message I received was: TypeError: openai.completions is not a function This occurred when running the follow ...

Using useRef with Typescript/Formik - a practical guide

Encountering Typescript errors while passing a ref property into my custom FieldInput for Formik validation. Specifically, in the function: const handleSubmitForm = ( values: FormValues, helpers: FormikHelpers<FormValues>, ) => { ...

Issues with displaying data in Angular Material table

I am having trouble displaying data in a table. The data shows up when I display it in another element, but not in the table. Here is my code: <mat-accordion *ngIf="posts.length > 0"> <mat-expansion-panel *ngFor="let post of p ...

Resizing inputs in Ionic 2 alert boxes

Hello all! I am currently working with the Ionic 2 framework and could use some assistance. I am attempting to make alert inputs that are multi-line or use textareas instead of single line inputs. Any guidance on how to achieve this would be greatly appr ...

Arrange the list by first names in the array using Ionic 3

What is the process for arranging a list by firstName from an array? This is my code in my.ts file: initializeItems(){ this.items = [ { avatar: '../../assets/imgs/profile1.jpg', firstName:'Sterlian', lastName:'Victorian ...

Encountering difficulty in retrieving value through the get method, resorting to interpolation. The value from the getTitle() method for 'this._title' is not being displayed

import { Component } from '@angular/core'; @Component({ selector: 'courses', template: '<h1>{{ getTitle() }}</h1>' ////issue with not displaying 'this._title' value??? }) export class CoursesCo ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

How to Disable Back Button During Angular 2 REST API Requests?

Within my Angular 2 application, a REST API call is made to process a functional flow and receive a response from the server. During this process, I want to prevent users from navigating using the browser's Back button. To achieve this, I have implem ...

Detecting if a string is in sentence or title case with a typeguard

When setting the sameSite property of a cookie, it must be either Strict, Lax, or None. However, the package I'm using uses lowercase values for this attribute. Therefore, I need to adjust the first letter of the string: let sentenceCaseSameSite: &quo ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

Is it possible to replicate a type in TypeScript using echo?

Is there any equivalent in TypeScript to the following code snippet? type TypeA = { x: number }; printType(TypeA); I have found a method that consistently enables TypeScript to provide a type description. const y = { x: 1, z: 'hello', }; ...

Invoking a nested class while declaring types in TypeScript

This is the specific format of data that I am in need of this.structure=[ { id: 1, name: 'root1', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { ...

NG2-smart-table Icons not appearing when using ngx-admin theme

In implementing my ng2-smart-table within an Angular project, I have utilized the ngx-admin theme for styling. Following the documented configuration steps involved installing necessary dependencies and importing required styles in my styles.scss file. Th ...

What is the best way to include a Web Service within an export variable in Angular 2 using TypeScript?

Is there a way to incorporate JSON data retrieved from the server into the export var HEROES: Hero[ ] function? Here is the link: https://angular.io/resources/live-examples/toh-5/ts/eplnkr.html In app/mock-heroes.ts, you will find the following data, im ...

retrieving information and parsing from an API using Ionic and Angular version 4

How can I extract data from the "data" field in my API using a function? getMenu() { return this.http.get('http://site.dev/api/menu/7'); } { "id": 26, "name": "Default", "title": "default", "pageelements": [ { "id": 15, ...

What is the best way to prevent URL modification in Angular?

Currently, I am working on a project with a specific page (let's call it localhost:XXXX/notification-page) and we want this to be the only URL that can be accessed. Any attempt to change the URL should redirect users back to the notification-page. As ...