import { AngularFireDatabase } from 'angularfire2/database';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CategoryService {
constructor(private db: AngularFireDatabase) { }
getCategories() {
return this.db.list('/categories', ref => ref.orderByChild('name')).valueChanges();
}
}
export class ProductsFormComponent {
categories$;
constructor(
private categoriesService: CategoryService,
private productService: ProductService,
private router: Router
) {
this.categories$ = categoriesService.getCategories();
}
save(product) {
this.productService.createProduct(product);
this.router.navigate(['/admin/admin-products']);
}
}
<div class="form-group">
<label for="category">Category</label>
<select ngModel name="category" #category="ngModel" id="category" type="text" class="form-control" required>
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.$key">
{{ c.name }}
</option>
</select>
<div class="alert alert-danger" *ngIf="category.touched && category.invalid">Category is required</div>
</div>
this.db.list('/categories', ref => ref.orderByChild('name')).valueChanges()
return an ListObservable which changes the $key value. There is a way to fix it by using snapShotChanges() method instead of valueChanges().
But for now, you can proceed by binding c.key instead of c.$key. Also, to make this work, you have to add an extra node of key with same category on your firebase database. See if this works for you.
Try the following changes
getCategories() {
return this.db.list('/categories', ref => ref.orderByChild('name')).snapshotChanges();
}
<select ngModel name="category" id="category" class="form-control">
<option value=""></option>
<option *ngFor="let c of categories$ | async" [value]="c.key">
{{c.payload.val().name}}
</option>
</select>
Let me know if it helps
It's working fine. Thanks...
But why you use "payload.val()".
I had the Same issue I solve it by changing [value]="c.$key"
to [value]="c.name"
and it worked I don't know if it causes other problems but so far seems to work for me
It's working fine. Thanks...
But why you use "payload.val()".
to show categories list in case you use c.name ur list didn't show
Most helpful comment
Try the following changes
getCategories() {
return this.db.list('/categories', ref => ref.orderByChild('name')).snapshotChanges();
}
Let me know if it helps