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