The ngModel directive seems to be failing to bind the select element in Angular 4

One of the challenges I am facing in my application involves a form that includes various data fields such as title, price, category (select), and imageUrl. I have successfully implemented ngModel for all fields except the select element. Strangely, when I log the form data using console.log(), every field has a value except for the select element, which returns undefined. I have already imported the AngularForms module in app.module.ts.

Below is the HTML code for my product-form-component:

<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>
        <div class="input-group">
          <span class="input-group-addon">$</span>
          <input ngModel name="price" id="price" type="number" class="form-control">
        </div>
      </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="iamgeUrl" id="imageUrl" type="text" class="form-control">
      </div>
      <button class="btn btn-primary">Save</button>
    </form>
    

This is the TypeScript file for product-form-component:

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

      @Component({
        selector: 'app-product-form',
        templateUrl: './product-form.component.html',
        styleUrls: ['./product-form.component.css']
      })
      export class ProductFormComponent implements OnInit {
        categories$;

        constructor(categoryService: CategoryService, private productService: ProductService ) { 
          this.categories$ = categoryService.getCategories();
        }

        ngOnInit() {
        }

        save(product) {
          console.log(product);
          this.productService.create(product);
        }
      }
    

This is the service file, product-service.ts:

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

      @Injectable()
      export class ProductService {

        constructor(private db: AngularFireDatabase) { }

        create(product) {
          return this.db.list('/products').push(product);
        }
      }
    

I am currently stuck on what might be causing this issue. Any detailed help would be greatly appreciated.

View my Firebase Database here: Firebase DB

Answer №1

The accurate answer is

[value]="c.$key"</global-code>. The errors occurred because I mistakenly used <code>[value]="c.key$"</local-code> instead.</p>
</div></answer2>
<exanswer2><div class="answer accepted" i="55956194" l="4.5" c="1556812345" a="YmlsbGFs" ai="9584746">
<p>This is the correct response: <code>[value]="c.$key"
. I made the mistake of assigning [value]="c.key$", which caused the error.

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

What causes the indexOf method to return -1 even when the values are present in the array?

Could someone explain why the indexOf() method returns -1 even though the values are present in the array? The includes() function also returns false for me. I feel like I must be missing something or forgetting a crucial detail. Any insights on why the ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Monitoring changes in a variable's value within an Angular 6 component

Within a page component, there exists an array; The array has new elements added to it in different locations within the component (in the createMessage() method and inside the subscriber of getIncomingMessagesStream()); Each time a new element is added to ...

AJAX, JavaScript, and hyphens

Can anyone help me understand why the ajax statement in my code does not accept the '-' symbol? I've had issues with this before and ended up modifying a lot of things on the backend of my site to use '_' instead, which worked. Is ...

What is the most efficient way to dynamically load a script file before proceeding with the rest of the code execution?

In my Angular home.component.ts file, I have added the script loading code as shown below: export class HomeComponent { constructor() { this.loadDynamicScript(); } public loadDynamicScript() { var script = document.createElement(&a ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

Link your 3D force graph node by attaching it

How can a link be attached to the nodes in 3d-force-graph (https://github.com/vasturiano/3d-force-graph) so that clicking on a node redirects the user to a specific or customized URL? ...

Show the checked items in the table based on the ID value stored in the array

When I click the button labeled Show checked if id values are 1 and 5, I encounter an issue in displaying checked items in the table based on their corresponding id value in the array. Essentially, I want to show the checked items in the table only if thei ...

developing a collection of Material UI text fields

My goal is to construct an accordion containing several textfield mui-components. I have developed a unique render function incorporating all the essential tags and syntax for creating a text field component. Now, I am looking to generate an array of text ...

Error: Unexpected termination of data in JSON file on line 2, starting at the first character

I keep encountering an error while trying to execute a basic JSON request. Check out the following PHP code that contains the data: <?php header('Content-Type: application/json; charset=utf-8'); $wealth = array( "name" => &q ...

Utilizing jquery to showcase the information in a neat and organized table

Having an input text box and a button, I am looking to display dummy data in a table when any number is entered into the input field and the button is clicked. Here is what I have tried: My Approach $("button#submitid").click(function () { $(&quo ...

Guide on setting up global typing for AngularJS in your project

I have been working on a project that initially used the deprecated typings method for incorporating Typescript definitions. I now want to transition to using the @types method instead. Currently, we have a typings.json file located in the root of the pro ...

The file-loader is able to organize images into separate folders when saving them. For example, an image file named "example.jpg" located in Project/Module

Hey there! I'm currently in the process of setting up a Webpack configuration that will generate files for each folder within my project. Unfortunately, creating a separate webpack.config file for each folder is not an option. So far, I have successf ...

AngularJS offers a function known as DataSource for managing data sources

During a recent project, I had to convert xml data to json and parse it for my app. One issue I encountered was related to the DataSource.get() function callback in the controller. After converting the xml data using a service, I stored the converted data ...

How can I set up Prettier to exclude a line following a specific pattern?

Is there a method to configure Prettier in Visual Studio Code to exclude lines following a specific pattern? Sometimes, I require a directive like /**@ts-ignore */ followed by a lengthy line. However, when Prettier formats the code, it introduces new line ...

Problem with deploying a Nextjs project on cPanel

I've been struggling to deploy a nextjs project on cPanel. The project consists of only one SSG page. I set the basePath in next.config.js to deploy the project, but I keep getting a 404 page not found error and the page keeps getting called in the ne ...

Using JQuery to make a GET request and receive a JSON response, then selecting particular objects

I am in the process of developing a straightforward web application. The concept involves users inputting a license plate number, which will then connect to an OpenData API based on Socrata that houses information about all registered vehicles in my countr ...

Using Angular 2+, learn how to effectively utilize and monitor the output emitter when utilizing the createComponent factory method

When I dynamically create a component in ParentComp, the code looks like this: const factory = this.resolver.resolveComponentFactory<ChildComp>(component); this.componentRef = this.container.createComponent(factory); this.componentRef.instance.dataC ...