Using ngFor results in duplicate instances of ng-template

I'm facing a challenge with the ngFor directive and I'm struggling to find a solution:

<ng-container *ngIf="user.images.length > 0">
   <div *ngFor="let image of images">
        <img
           *ngIf="image.isProfileImage; else noImage"
           [src]="image.path"
        />
   </div>
</ng-container>
                    
<ng-template #noImage>
   <img src="https://someplaceholder.com"/>
</ng-template>

Basically, I only want to display the profile image if it exists. If not, I want to show a placeholder image using a template. However, I noticed that in some instances when there are multiple non-profile images in the array, the template gets duplicated for each one instead of appearing just once. It seems like I am missing something obvious here. Any ideas?

Answer №1

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;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing React components within a controlled environment using cypress-react-unit-test

I'm currently facing a challenge in comprehending how to modify the props of a react component while utilizing cypress-react-unit-test. Below is a straightforward controlled input component: interface MyInputProps { inputVal: string onInputCh ...

What steps can I take to replicate a 'heap limit Allocation failed' error?

Context I encountered a challenging issue where my program displayed a FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory This occurred when the memory usage reached around 512 mb Scavenge (reduce) 507.8 (518.9) -> 507.2 ...

Conceal all div elements except for displaying the initial two

Can an entire div be hidden with only the first 2 entities visible? <div class="inline-edit-col"> <span class="title inline-edit-categories-label">Brands</span> <ul class="cat-checklist product_brand-checklist"> < ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Using Selenium and Python to download audio files that require JavaScript to load

Currently, I am in the process of developing a script to streamline the task of downloading text and audio files from a specific website using Python and Selenium. The targeted website is: (yyyymmdd) import requests from time import sleep from selenium ...

Understanding Node.JS: A Dive into Key Concepts

Forgive my lack of knowledge, but I'm really trying to grasp the differences between Node.js and Backbone.js. I believe I'm getting there, but could someone confirm this or guide me in the right direction? Node.js is a platform that can handle H ...

Unable to refresh the fullcalendar section following an ajax post click

Currently developing a calendar using fullcalendar. I have created an ajax button that retrieves events from another php page. The first click on the ajax button works fine, displaying a nice month calendar with events. However, my issue arises when I cl ...

The integration between React hook form and reactstrap input components is not functioning properly

Having an issue with react-hook-form and reactstrap. The component List.jsx is causing trouble: import { useContext, useEffect } from "react"; import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider'; import { Link } from "react- ...

react-responsive: The children of a Responsive component do not have the capability to receive props

Utilizing the typical scenario described in the README file: const Desktop = props => ( <Responsive {...props} minWidth={1680} maxWidth={2560} /> ) const LaptopL = props => ( <Responsive {...props} minWidth={1440} maxWidth={1679} /> ...

Unit testing is encountering issues due to errors with objects not being accepted as a React child component

Here is the code where I am testing the functionality of mytestFunc when a checkbox is checked. Checkbox - <input id="mycheck" type="checkbox" onClick={this.mytestFunc} /> mytestFunc function - mytestFunc = e => { const mockdata = this.stat ...

Transform the process.env into <any> type using TypeScript

Need help with handling logging statements: log.info('docker.r2g run routine is waiting for exit signal from the user. The container id is:', chalk.bold(process.env.r2g_container_id)); log.info('to inspect the container, use:', chalk.b ...

What is the best way to initiate a TouchEvent in a qunit test being run by grunt using only vanilla JavaScript?

I have implemented callbacks for different touch events that require testing. For example, the 'touchstart' event utilizes touch coordinates to configure a class member: NavigationUI.prototype.touchStart = function(evt) { this.interacting = ...

Altering or including new space variables within a custom Chakra-ui theme

Looking to customize spacing variables in a Chakra UI theme? I have successfully implemented various extensions, but changes to spacing are not being applied. const config: ThemeConfig = { initialColorMode: 'light', useSystemColorMode: false ...

Algorithm for searching and calculating with multiple words (Angular/Javascript)

As I work on loading a JSON file from the database containing two fields - words and grade, I face a challenge. Each word in the file is assigned a grade, for example, "true" has a grade of 1 while "lie" has a grade of -1. My goal is to take input from a t ...

Is Error k originating from Angular or Electron?

While utilizing Angular 10 in my Electron application, I encountered some errors after building a release version of the app. These errors are visible in the Chrome Inspector, but it's unclear whether they stem from Electron or Angular, and the messag ...

Angular 13: Problems arise with custom theme in Angular Material version 13

I've set up a custom theme palette for my project that works perfectly with version ^12.2.13 of Angular Material, but not with ^13.2.3. Here's the SCSS code for my custom theming: my-custom-theme.scss @import '~@angular/material/theming&apo ...

Unable to modify the model of the directive

I'm facing an issue where additional elements added to my array within a controller of a directive are not being displayed in the view. What's even more frustrating is that when I print my model, it doesn't reflect the new elements that have ...

Guide to implementing a DataTable in MVC4 UI using jQuery

Looking to set up a DataTable using jQuery similar to the one shown in this image: https://i.stack.imgur.com/DNUcd.png I'm not very comfortable with jQuery, so please be patient and avoid asking me what I've tried. I don't know how to stru ...

Learn the step-by-step process of graphing equations in React similar to Desmos

I am currently attempting to create a graph of an equation based on user input, similar to how it is done on Desmos () For example While I have come across a function plotting tool at , I have encountered difficulties when trying to plot equations contai ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...