There are multiple methods
Option 1: Using *ngIf
You could check if the array is defined before using it. Since a single element can't have two structural directives, I'd wrap it in a <ng-container>
.
<ng-container *ngIf="!!getCartDetails && getCartDetails.length">
<mat-card *ngFor="let getCartDetail of getCartDetails" style="margin-bottom: 1em; " >
<div class="card-container">
<mat-card-title><h3>{{getCartDetail.title1}}</h3> </mat-card-title>
</div>
</mat-card>
</ng-container>
!!getCartDetails
checks if the variable getCartDetails
is defined. Check here for more info on double-bang !!
.
getCartDetails.length
checks if the array is empty
Here the <mat-card>
would not be rendered when the condition fails.
Option 2: Safe navigation operator ?.
You could use safe navigation operator ?.
to check if the variable is defined before accessing it's properties.
<mat-card *ngFor="let getCartDetail of getCartDetails" style="margin-bottom: 1em; " >
<div class="card-container">
<mat-card-title><h3>{{getCartDetail?.title1}}</h3> </mat-card-title>
</div>
</mat-card>
Here the <mat-card>
would be rendered with an empty <mat-card-title>
when the title1
is unavailable.
Option 3: Using ||
Statements inside Angular template interpolation {{ }}
are valid Typescript expressions, so you could use ||
to use an alternate value when the expression fails.
<mat-card *ngFor="let getCartDetail of getCartDetails" style="margin-bottom: 1em; " >
<div class="card-container">
<mat-card-title><h3>{{ getCartDetail.title1 || '' }}</h3> </mat-card-title>
</div>
</mat-card>
Here the <mat-card>
would be rendered with an empty <mat-card-title>
when the title1
is unavailable.