Seeking to retrieve data from Firebase's real-time database by passing values in an input form, I encountered an issue whenever I attempt to utilize
[(ngModel)]="product.title"
.
ERROR TypeError: Cannot read property 'title' of null
This code snippet is extracted from my product-form.component.html:
<div class="row">
<div class="col-md-6">
<form #f="ngForm" (ngSubmit)="save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
<div class="alert alert-danger" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
... (other input fields)
<button class="btn btn-primary">Save</button>
<button type="button" (click)="delete()" class="btn btn-danger ml-3">Delete</button>
</form>
</div>
<div class="col-md-6">
<div *ngIf="product.title" class="card" style="width: 18rem;">
<img class="card-img-top" [src]="product.imageUrl" *ngIf="product.imageUrl">
<div class="card-body">
<h5 class="card-title">{{ product.title }}</h5>
<p class="card-text">{{ product.price | currency:'USD': true }}</p>
</div>
</div>
</div>
This snippet showcases a portion of my product-form.component.ts file:
import { Product } from './../../models/product';
... (imports)
@Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
... (properties and constructor details)
save(product) {
if (this.id) this.productService.update(this.id, product);
else this.productService.create(product);
this.router.navigate(['/admin/products']);
}
delete() {
... (deletion logic)
}
ngOnInit(): void {
}
}
This excerpt represents the contents of my product.service.ts file:
import { AngularFireDatabase } from '@angular/fire/database';
... (imports)
@Injectable({
providedIn: 'root'
})
export class ProductService {
... (methods for CRUD operations)
}
Finally, below is the interface defined in my product.ts file:
export interface Product {
title: string;
price: number;
category: string;
imageUrl: string;
}
Error message displayed in the browser:
core.js:4352 ERROR TypeError: Cannot read property 'title' of null
at ProductFormComponent_Template (product-form.component.html:6)*
In need of assistance to tackle this issue. Your help would be greatly appreciated!