If you find yourself stuck in an ngFor loop, don't worry - there's always a solution waiting for you.
A handy method you can use is to create a function within your component that iterates through the array to check for profile images. Once you've identified them, you can tweak your HTML code accordingly by determining whether the array contains any profile images. If not, you can opt to display the ngTemplate instead.
Take a look at an example below:
<ng-container *ngIf="user.images.length">
<ng-container *ngIf="containsProfileImage(); else noImage">
<div *ngFor="let image of images">
<img
*ngIf="image.isProfileImage"
[src]="image.path"
/>
</div>
</ng-container>
</ng-container>
<ng-template #noImage>
<img src="https://someplaceholder.com"/>
</ng-template>
containsProfileImage(): boolean{
let returnVal = false;
this.user.images.forEach(image => {
if (image.isProfileImage) {
returnVal = true;
return;
}
}
return returnVal;
}
UPDATE: An Alternative Approach
In response to Chris G's suggestion, another way to tackle the issue is by filtering out images with profile images and checking the length of the filtered array. This will help you determine if there's at least one image in the list. If not, simply display the noImage
ngTemplate.
<ng-container *ngIf="user.images.length">
<ng-container *ngIf="filteredImagesLength; else noImage">
<div *ngFor="let image of images">
<img
*ngIf="image.isProfileImage"
[src]="image.path"
/>
</div>
</ng-container>
</ng-container>
<ng-template #noImage>
<img src="https://someplaceholder.com"/>
</ng-template>
get filteredImagesLength(): number {
return user.images.filter(i => i.isProfileImage)?.length;
}