Issue
I am trying to get product data from firebase database and displaying its properties in browser. I have defined product object as empty initially and when I get data from firebase and then show it by using two way binding like [(ngModel)]="product.title". but get the above mentioned error. please help.
product.service.ts
getProduct(productId){
return this.db.object('/products/' + productId ).valueChanges();
}
}
product-form.component.ts
export class ProductFormComponent implements OnInit{
categories$;
product={};
constructor(
private router: Router,
private route :ActivatedRoute,
private categoryService: CategoryService,
private productService:ProductService) {
this.categories$ = categoryService.getCategories();
let id = this.route.snapshot.paramMap.get('id');
if (id) this.productService.getProduct(id).pipe(take(1)).subscribe(p => this.product = p);
}
product-form-component.html
<div class = "row">
<div class="col-md-6">
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" name="title"
type="text" class="form-control" placeholder="Name of the Product"
id="title" required> <!-- Error [(ngModel)]="product.title" , Property 'title' does not exist on type '{}'-->
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required
</div>
</div>
Solution
You have defined your type as any. A better way would be to define the type or simply let typescript infer the type, something like
export class ProductFormComponent implements OnInit{
categories$ = categoryService.getCategories();
product = {
title: ''
}
constructor(
private router: Router,
private route :ActivatedRoute,
private categoryService: CategoryService,
private productService:ProductService) {
let id = this.route.snapshot.paramMap.get('id');
if (id) {
this.productService.getProduct(id).pipe(
take(1)
).subscribe(p => this.product = p);
}
}
Answered By - Owen Kelvin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.