Unspecified behavior for a dropdown menu within an Angular form

I'm a newcomer to Angular and currently struggling with displaying the selected values of form elements in the console. Surprisingly, all other elements get printed except for the select list element which shows up as undefined. Here's an overview of my code in category.services.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from '@angular/fire/database';

@Injectable({
  providedIn: 'root'
})
export class CategoryService {

  constructor(private db: AngularFireDatabase) { }

  getCategories(){
    return this.db.list('/categories').valueChanges()
      }
}

product-form.component.ts

import { Component, OnInit } from '@angular/core';
import { CategoryService } from 'src/app/category.service';

@Component({
  selector: 'app-product-forum',
  templateUrl: './product-forum.component.html',
  styleUrls: ['./product-forum.component.css']
})
export class ProductForumComponent implements OnInit {

  categories$
  constructor(categoryService: CategoryService) {
    this.categories$=categoryService.getCategories()
   }

  save(product){
    console.log(product)
  }

  ngOnInit() {
  }

}

product-form.component.html

<form #f="ngForm" (ngSubmit)="save(f.value)">
    <div class="form-group">
        <label for="title">Title</label>
        <input ngModel name="title" id="title" type="text" class="form-control">
    </div>
    <div class="form-group">
            <label for="price">Price</label>
            <input ngModel name="price" id="price" type="number" class="form-control">
    </div>
    <div class="form-group">
            <label for="category">Category</label>
            <select ngModel name="category" id="category" class="form-control">
                <option value=""></option>
                <option *ngFor="let c of categories$ | async" [value]="c.$key">
                    {{ c.name }}
                </option>
            </select>
    </div>
    <div class="form-group">
            <label for="imageUrl">Image Url</label>
            <input ngModel name="image" id="imageUrl" type="text" class="form-control">
    </div>
    <button class="btn btn-primary">Save</button>
</form>

https://i.sstatic.net/nsywS.png

Upon clicking the SAVE button,

CONSOLE

{title: "title", price: 10, category: "undefined", image: "imageUrl"}
category: "undefined"
image: "imageUrl"
price: 10
title: "title"
__proto__: Object

CATEGORIES https://i.sstatic.net/YD8xl.png

Answer №1

Make sure to utilize the ngValue attribute rather than value in the following manner.

  <select ngModel name="category" id="category" class="form-control">
    <option value=""></option>
    <option *ngFor="let c of categories$ | async" [ngValue]="c.name">
        {{ c.name }}
    </option>
  </select>

Answer №2

Consider using c.name instead of c.$key when replacing it in the code snippet provided. If that doesn't solve the issue, please provide a sample JSON for further assistance.

<select name="category" id="category" class="form-control">
            <option value=""></option>
            <option *ngFor="let c of categories$ | async" [ngValue]="c.name">
                {{ c.name }}
            </option>
          </select>

Answer №3

<div class="dropdown-menu" id="categoryDropdown">
    <a href="#" class="dropdown-item">All Categories</a>
    <ng-container *ngFor="let category of categoriesList$ | async">
        <a href="#" class="dropdown-item">{{ category.name }}</a>
    </ng-container>
</div>

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

Guidelines for generating and printing a receipt on a thermal printer using react.js and NodeJs?

After creating an office application to manage a supermarket using Windev, my client now wants to enable remote access and control over the internet. To achieve this, I am considering transforming the application into a web application using React.js in th ...

Converting a base64 string to a PNG format for uploading to an S3 bucket from the frontend

Feeling a bit overwhelmed here, hoping this isn't just a repeat issue. I've come across similar problems but none of the solutions seem to be working for me at the moment. I'm currently utilizing react-signature-canvas for allowing users to ...

Dealing with repeated parameters in a URLHow can you handle duplicate

My Ajax select input dynamically changes the URL without refreshing the page. However, I have encountered an issue where repeated parameters stack in the URL when the select input is changed multiple times: [domain]/find.php?cat=1#pricemin=10&pricem ...

store the id of each li element dynamically into an array

In my code, a list is generated dynamically and each list item has a special id. I am trying to store each li "id" in one array. This is JavaScript code: var i = 0; $("ul#portfolio li").each(function(eval) { var idd = new Array(); idd[i] = $(this ...

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

How come the deleteOne and findById methods in mongoose are able to function properly even after the document has

During my development of an API using nodejs to interact with a MongoDB database, I encountered a peculiar issue after deleting a document. My API consists of various endpoints for retrieving all animals in the database, fetching a specific animal using i ...

Ways to determine the generic type of a property value from a decorated property within a decorator

While experimenting with some code, I encountered an issue where the generic type of a property value wasn't being resolved correctly when changing from TValue to (t: TValue) => TValue. Instead of being recognized as the expected number, it was now ...

Exploring the functioning of Dependency Injection in components that are dynamically loaded

Given the setup of my components and services, with both Module A and B being lazy loaded, I have a scenario where the component container in Module A is dynamically loading Component B1. How does dependency injection work in this case? Does it look for de ...

Troubles with Promise.all and json() in JavaScript causing errors being logged as "invalid function"

I'm experiencing some difficulties with the "Promise.all" method. Essentially, I have an array of URLs (here is a simple one if you want to test it: const urlArray = [ "https://coverartarchive.org/release/985adeec-a1fd-4e79-899d-10c54b6af299&qu ...

Comparing boolean values in React JS

I am working with a React JavaScript code in which I am iterating through a series of boolean values. The issue I am facing is that when 'data.nextrow' is false, I expect nextrow1 to also be false but it ends up being set to true instead. co ...

Tips for verifying that a WebSocket message is a JSON string and preventing any JSON.parse errors

After diligently searching for a solution to handle invalid JSON.parse calls, particularly in the context of WebSocket messages without using the try/catch block due to performance concerns. I've successfully transitioned my RESTful API to a WebSocke ...

Using the ES6 filter method to iterate through a double nested array of objects

Struggling with filtering a nested array of objects and specifically stuck at the filter part. Any idea on how to eliminate one of the marks? this.state = { data: [ { id: 1, name: "Main", subs: [ { id: "jay", ...

Using JavaScript to ensure that a div is not hidden on page load if a checkbox is unchecked

Upon inspecting a page, I am implementing a script to check if a checkbox is selected. If not selected, the goal is to hide a specific div element. While troubleshooting this issue, I suspect the problem may be due to the lack of an inline element within t ...

Is there a way to utilize a single EventBus for both a Java and GWT project concurrently?

Currently, I am working on a java project that utilizes the Guava EventBus. My goal is to integrate this code into a GWT project without having to rewrite it entirely. While I am aware that GWT comes with its own built-in EventBus, making changes to my Jav ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...

Bcrypt.compare function working in code but not functioning in chai/mocha tests

I have integrated node.js backend into my project. For encrypting passwords, I am utilizing the bcrypt library. To compare the string password from the request with the hashed password in the database, I am using the bcrypt.compare function. The bcrypt.com ...

What is the correct method for checking the balances of various tokens in my MetaMask wallet?

I've been trying to figure out how to check the balance of Alpaca tokens in my MetaMask wallet. After doing some research, I came across a code snippet that I tried to use but it ended up throwing an error: TypeError: contract.balanceOf is not a fun ...

Designing a user interface for unlimited nested components with optional properties

I am currently working on creating an interface for the specific object type shown below. "Condition": { "And": { "Or": { "userData": [ { "name": "Alex", &q ...

Encountering an error message stating "The variable 'App' is declared but not used" when running the index.tsx function

This React project is my attempt to learn how to use a modal window. The tutorial I've been following on YouTube uses JavaScript instead of TypeScript for their React project. However, I'm facing some challenges. Could you possibly help me ident ...

Remove files from the server using an AJAX request

I am attempting to delete files on the SERVER using JavaScript, and I have already consulted the advice provided in this JavaScript file deletion thread My current JavaScript code looks like this: deleteFile = function() { return $.ajax({ url: "de ...