Reputation: 23
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.
getProduct(productId){
return this.db.object('/products/' + productId ).valueChanges();
}
}
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);
}
<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>
Upvotes: 2
Views: 2213
Reputation: 2201
Create an interface for the product object and add type to the product
variable
interface Product {
title: string
// otherProps: string
}
export class ProductFormComponent implements OnInit {
categories$ = categoryService.getCategories();
// added a definite assertion telling TS that it will be assigned before access
private product!: Product
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);
}
}
}
Upvotes: 0
Reputation: 15083
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);
}
}
Upvotes: 1