Home > Mobile >  ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl') Angular material
ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl') Angular material

Time:02-12

When I write this line of html code:

<td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>

The console throws the following error:

ERROR TypeError: Cannot read properties of undefined (reading 'imageUrl')

imageUrl is of type string and it is an url. I'm using Angular material. How can I deal with it?

.html file:

<table>

        <!-- Image Column -->
  <ng-container matColumnDef="img">
    <th mat-header-cell *matHeaderCellDef></th>
    <td> <img align="center" [src]="productByBarCode.imageUrl" /> </td>
  </ng-container>

...

</table>

.ts file:

export class ProductDetailsComponent implements OnInit {
  public productByBarCode!: Product;
  displayedColumns = ['img', 'name', 'description', 'price', 'quantity', 'add to cart'];
  constructor(private _snackBar: MatSnackBar, private shared: SharedService, private productService: ProductService) { }

  ngOnInit(): void {
    this.shared.castByBarCode.subscribe(productByBarCode=>this.productByBarCode=productByBarCode);
...
}

CodePudding user response:

I can only assume that your "shared" service isn't resolving productByBarCode variable before view tries to reach it. In that case your code is trying to resolve imageUrl from null.

You can just *ngIf check if productByBarCode is truthy/falsy like this:

<td>
    <img *ngIf="productByBarCode" align="center [src]="productByBarCode.imageUrl" />
</td>

After this if your image still isn't resolving, just console.log your productByBarCode variable to check whats inside :)

  • Related