Having an issue where one of my properties is showing as "undefined" even though it is defined. Can't seem to find a solution:
I have a parent component with the following data:
@Component({
selector: "app-my-products",
templateUrl: "./my-products.component.html",
styleUrls: ["./my-products.component.css"]
})
export class MyProductsComponent implements OnInit {
watched: WatchedProduct[] = [];
products: Product[] = [];
watchedProducts: Product[] = [];
ratings: ProductAvarageRating[] = [];
//the data retrieval works fine
In Parent.Component.html, I call two child components like this, passing in the data:
<div>
<app-my-products-ratings
[watchedProducts]="watchedProducts"
[ratings]="ratings"
></app-my-products-ratings>
<app-my-products-watched
[watchedProducts]="watchedProducts"
></app-my-products-watched>
</div>
MyProductsWatched.component.ts
has the following structure:
@Component({
selector: "app-my-products-watched",
templateUrl: "./my-products-watched.component.html",
styleUrls: ["./my-products-watched.component.css"]
})
export class MyProductsWatchedComponent implements OnInit {
products: Product[] = [];
watched: WatchedProduct[] = [];
selectedProduct = new Product();
@Input() watchedProducts: WatchedProduct[] = []; //data from Parent here
And its html looks like this:
<mat-list-item *ngFor="let product of watchedProducts">
<button mat-button>{{ product.name }}</button>
</mat-list-item>
This part works fine. However, in MyProductRatings.component.html
, I encounter an error where one of the properties from ratings
is undefined.
The Component for MyProductRatings
is structured as follows:
@Component({
selector: "app-my-products-ratings",
templateUrl: "./my-products-ratings.component.html",
styleUrls: ["./my-products-ratings.component.css"]
})
export class MyProductsRatingsComponent implements OnInit {
@Input() watchedProducts: WatchedProduct[] = [];
@Input() ratings: ProductAvarageRating[] = []; //data from parent here
The corresponding HTML is:
<div>
<mat-selection-list>
<mat-list-item
*ngFor="
let product of (watchedProducts | search: searchText);
let i = index
"
>
<button mat-button>{{ watchedProducts[i].name }}</button>
{{ ratings[i].avarageRating }}
</mat-list-item>
</mat-selection-list>
</div>
My goal is to fetch the property named avarageRating
from ratings
based on the index
during the *ngFor
loop.
Currently, I have 2 items in watchedProducts
. The error message in MyProductRatings.component.html
reads:
ERROR TypeError: Cannot read property 'avarageRating' of undefined
Despite this error, the rating actually displays correctly.
My question is, what am I doing wrong that is causing these errors to appear in the console?