There are various approaches
Method 1: Employing *ngIf
You can verify if the array exists before utilizing it. Since a single element cannot have two structural directives, enclosing it in an <ng-container>
would be necessary.
<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 for the presence of the variable getCartDetails
. More information on double-bang !!
can be found here.
getCartDetails.length
confirms if the array is empty
In this scenario, the <mat-card>
will not display when the condition is not met.
Method 2: Utilizing Safe Navigation Operator ?.
The safe navigation operator ?.
can be employed to ensure that the variable is defined before accessing its 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>
will be displayed with an empty <mat-card-title>
if title1
is inaccessible.
Method 3: Using ||
Expressions within Angular template interpolation {{ }}
are valid Typescript expressions, allowing you to utilize ||
to specify an alternative value if 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>
In this case, the <mat-card>
will be shown with an empty <mat-card-title>
if title1
is not available.