Reputation: 89
I'm an Angular beginner and I'm trying to print values of form elements selected in console. Every other element like got printed but the select
selected list element shows undefined
. Here's my code
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>
After I hit SAVE button,
CONSOLE
{title: "title", price: 10, category: "undefined", image: "imageUrl"}
category: "undefined"
image: "imageUrl"
price: 10
title: "title"
__proto__: Object
Upvotes: 2
Views: 700
Reputation: 1
<select name="category" ngModel id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.name">
{{ c.name }}
</option>
</select>
Upvotes: 0
Reputation: 5265
Use ngValue
instead value
as follows.
<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>
Upvotes: 1
Reputation: 415
try this replace c.$key with c.name or just c. it should work. if not please share your sample JSON.
<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>
Upvotes: 0