What causes the select dropdown to display an empty default in Angular 8 following an HTTP request?

I have created a simple HTML code to populate array elements in a dropdown list, with the default value being fetched from an HTTP service during the ngOnInit lifecycle hook. However, I am encountering an issue where the default value is displayed as empty in the dropdown.

Here is my HTML:

<select class="form-control" name="chocolate"
   [(ngModel)]="selectedChocolateId">
   <option *ngFor="let chocolate of chocolates" [ngValue]="chocolate.id">
   {{chocolate.name}}
   </option>
</select>

And here is my TypeScript code:

public selectedChocolateId:number;

ngOnInit() {
    this._chocolateService.GetChocolateId().subscribe(data => {
        this.selectedChocolateId = data;
    })
}

public chocolates = [
  { id:1, "name":"Diary Milk"},
  { id:2, "name":"Five star"}
];

When I execute the code, I notice that the default value in the dropdown appears empty. However, upon logging the fetched value from the service, I can see that it is being retrieved successfully. Any assistance would be greatly appreciated!

Answer №1

Chances are that the data is not in numerical format, which is why it's having trouble finding the correct value.

Visit this link for more information.

To resolve this issue, simply wrap the data with Number().

Answer №2

When working with objects and encountering issues with select.Model bindings not functioning correctly, Angular offers a solution through the compareWith input. This input allows you to provide a function, compareFn, which informs Angular on how to compare values.

Give this a try:

component.html

 <select [compareWith]="compareFn" class="form-control" name="chocolate"
       [(ngModel)]="selectedChocolateId">
       <option *ngFor="let chocolate of chocolates" [ngValue]="chocolate.id">
       {{chocolate.name}}
       </option>
    </select>

component.ts

compareFn(c1, c2): boolean {
    return c1 && c2 ? c1.id === c2.id : c1 === c2;
}

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

An HTML table featuring rows of input boxes that collapse when the default value is not filled in

My table is populated with dynamic rows of input boxes, some of which may have a default value while others return an empty string ''. This causes the table to collapse on those inputs. <tr *ngFor="let d of displayData"> < ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

PrimeNG's Angular component pTree TreeNode

Is there a way in Angular to retrieve the positions of nodes within a TreeNode hierarchy based on their display order? I have data structured as TreeNode objects, which include children that can branch off further. How can I access these nodes according t ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...

It is not possible to transform Next.js into a Progressive Web App (P

Can someone assist me with PWA implementation? I tried running npm run build, but it was unsuccessful. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdbaacbface0abbfa2a3b98dfde3fce3fd">[email protected]</a> ...

What is the preferred method for validating an Angular form - ng-model or form input name?

When it comes to validating an input field and providing feedback, there are two methods that I have noticed: <form name="myform" ng-submit="myform && myFunc()"> <input name="foo" ng-model="foo" ...

Repeating percentages displayed in a progress bar

I created a responsive progress bar, but the progress values are repeating. I only want the central value to be displayed. Any suggestions on how to fix this issue? DEMO <div id="tab1"> <dx-data-grid class="tableTask" [dataSource]="datas" ...

Update the options in a dropdown menu after submitting a modal form

In my scenario, I have a modal form called "AddProductComponent" which is utilized within the "AddServiceRecordsComponent". export class AddProductComponent implements OnInit { id!: string; isAddMode: boolean = false; constructor(private fb: FormBuilder, ...

Utilizing Angular 5 alongside the powerful ngx-cookie library and configuring it all within the system

Currently in the process of upgrading a project from AngularJS 1 to Angular 5. In need of a package for cookie manipulation, I came across ngx-cookie. However, facing a hurdle as I cannot alter systemjs.config.js as per the instructions provided, given t ...

Angular 4 - The bindings are restricted from having assignments within them

Looking to include a CSS selector as an @Input in my component. To achieve this, I need to use the following syntax for passing a css selector: <mds-datetime-picker [inLine]="true" [targetSelector]='[data-name="target"]'></mds-datet ...

Updating Angular 5 Views Dynamically Using a While Loop

I am facing an issue in my app where I have a progress bar that updates using a while loop. The problem is that the view only updates after the entire while loop has finished running, even though I am successfully changing the update progress value with ea ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

Import JSON data into Angular 2 Component

After much effort, I have finally figured out how to load JSON data into an Angular 2 Component. datoer.service.ts: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from ...

Using conditional CSS values in Angular 8

I am currently working on a parent component and child component setup, where I am utilizing the child component's selector to display it within the parent component. Here is my child component's HTML: <div class="main-container" [n ...

Using checkboxes for filtering in a React application

Here are the data sets I am working with: const dataSet = [ { id: 1, title: 'object1', published: true, }, { id: 2, title: 'object2', published: true, }, { id: 3, title: 'object3', ...

Injecting Dependencies with Angular 2 and the Ability to Include Optional Parameters

One issue I'm facing is that I have multiple components in my Angular 2 application that require the same dependency. This specific dependency needs a string for the constructor. How can I instruct angular2 to use a specific instance of this type for ...

What is the correct method for packaging and using a TypeScript library built with webpack?

Recently delving into the world of TypeScript, I find myself struggling to grasp how to create a TypeScript library that can be utilized in another TypeScript module through webpack. This particular library is meant to be functional within a browser envir ...

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Is it possible to perform an "input transformation" (a reverse of piping) within Angular 2?

Currently, I have an array of keywords stored as a property within my model. The goal now is to display this array as a comma-separated string in an input field and then convert it back into an array when the user makes changes. I've already implemen ...

Transmitting form data inputted by the user to a modal that resides in the same component, all without the need for child or parent components or

In need of a solution where users can input answers to questions and have all the entered data displayed in a popup alongside the respective question. If a user chooses not to answer a question, I do not want that question or any related information to be ...