Reputation: 67
I am making a form in Angular5 using firebase in backend. The form contains few input fields and a dropdown.
I'm able to populate values ({{ c.name }}) in dropdown options but value attribute of option is coming empty which I'm trying to populate using c.$key.
Below is the HTML part:
<form #f="ngForm" (ngSubmit)="save(f.value)">
<!-- other input fields here -->
<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>
</form>
Here is my component:
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
constructor(categoryService: CategoryService) {
this.categories$ = categoryService.getCategories();
}
ngOnInit() {
}
save(product) {
console.log(product);
}
}
Service:
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class CategoryService {
constructor(private db: AngularFireDatabase) { }
getCategories() {
return this.db.list('/categories', ref => ref.orderByChild('name')).valueChanges();
}
}
I'm printing value of form json on console. The value of category is coming undefined.
{title: "Title", price: 10, category: "undefined", imageUrl: "xyz"}
Please guide me what am I missing.
Upvotes: 1
Views: 771
Reputation: 11
$key
has been deprecated. Use snapshotChanges()
instead.
category.service.ts
getCategories() {
return this.db
.list('/categories', (ref) => ref.orderByChild('name'))
.snapshotChanges()
.pipe(
map((actions) => {
return actions.map((action) => ({
key: action.key,
val: action.payload.val(),
}));
}));
}
app.component.html
<option *ngFor="let c of categories$ | async" [value]="c.key">
{{ c.val.name }}
</option>
Upvotes: 1