Using ngFor to display a default image

My latest project involved creating a table that displays various products along with their corresponding images. Everything was working smoothly until I encountered an issue.

In instances where a product is created without an associated image, I decided to use a default image instead. However, the problem lies in the fact that the default image is showing up alongside the actual image space, making it seem like there's a problem when all I want is for the default image to be displayed alone.

Has anyone else experienced this issue and knows why it might be happening?

https://i.sstatic.net/FZlMu.png

HTML

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
          <div *ngIf="imagMap.get(product.id) == null">
              <img src="./assets/semimagem.png" class="imgTable img-fluid" alt="">
            </div>
        <img [src]="imagMap.get(product.id)" class="imgTable img-fluid">
      </td> 
  </tr> 
</table> 

Answer №1

Make sure to familiarize yourself with ngIf, as it is a crucial element in Angular that provides basic logic for your template.

Instead of using an empty <div>, consider using ngContainer and referencing a ngTemplate for the else condition.

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
        <ng-container *ngIf="imagMap.get(product.id) == null; else productImage">
              <img src="./assets/semimagem.png" class="imgTable img-fluid" alt="">
        </ng-container>
        <ng-template #productImage>
              <img [src]="imagMap.get(product.id)" class="imgTable img-fluid">
        </ng-template>
      </td> 
  </tr> 
</table> 

Another option is to use a logical OR:

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
         <img [src]="imagMap.get(product.id) || './assets/semimagem.png'" class="imgTable img-fluid">
      </td> 
  </tr> 
</table> 

Answer №2

To ensure the image is displayed only when the default image is not present, you can make adjustments to the code like this:

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
          <div *ngIf="imagMap.get(product.id) == null; else nonDefault">
              <img src="./assets/semimagem.png" class="imgTable img-fluid" alt="">
            </div>
        <ng-template #nonDefault>
            <img [src]="imagMap.get(product.id)" class="imgTable img-fluid">
        </ng-template>
      </td> 
  </tr> 
</table> 

For more information on using ng if else, visit this link.

Answer №3

Here is a suggestion for the default image:

<img src="assets/semimagem.png" class="imgTable img-fluid" alt="">

Make sure that semiagem.png is present in the assets folder.

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
          <div *ngIf="imagMap.get(product.id) == null">
              <img src="assets/semimagem.png" class="imgTable img-fluid" alt="">
            </div>
        <img [src]="imagMap.get(product.id)" *ngif="imagMap.get(product.id) !== null" class="imgTable img-fluid">
      </td> 
  </tr> 
</table> 

Answer №4

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
        <ng-template #productImage>
              <img [src]="imagMap.get(product.id) != null 
 ? imagMap.get(product.id) :./assets/semimagem.png" class="imgTable img-fluid">
        </ng-template>
      </td> 
  </tr> 
</table> 

Alternatively, You Could Try This Approach:

<table class = "gfg" *ngFor="let product of products; let  a = index;"> 
  <tr> 
      <td class = "geeks">
        <ng-template #productImage>
              <img [src]="imagMap.get(product.id) 
 ? imagMap.get(product.id) : ./assets/semimagem.png" class="imgTable img-fluid">
        </ng-template>
      </td> 
  </tr> 
</table> 

Answer №5

Follow this method:

<img [attr.src]="imagMap.get(product.id)?imagMap.get(product.id):defaultImage" />

within your typescript file

defaultImage: any = 'assets/semimagem.png';

The function imagMap.get(product.id) needs to either return a value or null

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

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...

Angular 7+: Trouble with displaying images from assets directory

Details regarding my Angular version: Angular CLI: 7.3.9 Node: 10.15.3 OS: win32 x64 Angular: 7.2.15 ... animations, common, compiler, compiler-cli, core, forms ... language-service, platform-browser, platform-browser-dynamic ... rout ...

Tips on applying the "activate" class to a Bootstrap navbar in Angular 2 when implementing page anchor navigation

As I work on my single-page website using Angular 2 and Bootstrap 4, I have successfully implemented a fixed navbar component that remains at the top of the page. Utilizing anchor navigation (#id), the navbar allows smooth scrolling to different sections o ...

Nesting two ngFor loops in Angular using the async pipe leads to consistent reloading of data

In my Angular application, I am trying to retrieve a list of parent elements and then for each parent, fetch its corresponding children (1 parent to n children). Parent Child1 Child2 Parent Child1 Parent3 Child1 Child2 Child3 Initially, I succes ...

Unable to locate the JSON file in the req.body after sending it through an HTTP post request

I have been working on implementing a new feature in my application that involves passing a JSON file from an Angular frontend to a Node backend using Express. The initial code reference can be found at How do I write a JSON object to file via Node server? ...

Tips for managing unfinished transactions through Stripe

I have successfully set up a checkout session with Stripe and included a cancel_url as per the documentation. However, I am facing an issue where the cancel_url is only triggered when the user clicks the back button provided by Stripe. What I want to achie ...

The power of Vue reactivity in action with Typescript classes

Currently, I am working on a Vue application that is using Vue 2.6.10 along with Typescript 3.6.3. In my project, I have defined a Typescript class which contains some standard functions for the application. There is also a plugin in place that assigns an ...

Websites experiencing horizontal scrolling functionalities

I have noticed that in my angular project, the website becomes horizontally scrollable when I log in. This only happens after logging in, and does not occur beforehand. I'm using angular calendars and Bootstrap for styling. What could be causing this ...

Managing Image Files in Node.js-Express with MongoDB and Displaying Them in Angular8 Interface

This Employee Management System allows for the uploading and storage of profile images of employees in an API server with a defined path. The implementation involves the following steps: https://i.sstatic.net/JBgb0.png Step 1: Making an API Server Reque ...

The API endpoint code functions perfectly in Express, but encounters an error when integrated into Next.js

Express Code: app.get('/', async (req, res) => { const devices = await gsmarena.catalog.getBrand("apple-phones-48"); const name = devices.map((device) => device.name); res.json(name); }) Nextjs Code: import {gsmarena} ...

I am currently leveraging Angular 17, but I have yet to enable Vite. Can anyone guide me on

Despite having the most recent version of NX and Angular, my app has not yet integrated Vite. I've come across online suggestions on how to enable it, but none of them make sense to me because my project doesn't have an angular.json file. Instead ...

Did not adhere to regulations

Currently, I am in the process of developing a React app. However, when I attempt to initiate my project using npm start in the terminal, I encounter an error message on the browser. https://i.stack.imgur.com/wej1W.jpg Furthermore, I also receive an erro ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

Assign a value of 0 to the ngModel if it is empty

I am trying to ensure that when the value is null, it defaults to 0. At the moment, I am utilizing Angular PrimeNG components. <p-calendar [(ngModel)]="model.start_time" [timeOnly]="true" placeholder="00:00"></p-calen ...

Tips for accessing the 'index' variable in *ngFor directive and making modifications (restriction on deleting only one item at a time from a list)

Here is the code snippet I'm working with: HTML: <ion-item-sliding *ngFor="let object of objectList; let idx = index"> <ion-item> <ion-input type="text" text-left [(ngModel)]="objectList[idx].name" placeholder="Nam ...

Bar chart in Highcharts vanishing following the update from version 10.2.1 to 10.3.1

I've been in the process of updating my highcharts to the latest version, but I've hit a roadblock. Specifically, I have a bar chart set up with the following configuration: { chart: { type: 'bar', ...

Error in Angular 12: Unable to access 'bootstrap' property from null

During the upgrade process of my Angular 10 application to Angular 12, I encountered an error that says: TypeError: Cannot read property 'bootstrap' of null Below are the files related to my Angular setup: tsconfig.json { "compileOnSave& ...

Fix for sorting issue in Angular 4.4.x mat-table header

I am facing an issue with my mat-table sorting header. I have followed the examples and decorated the columns accordingly: <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell> & ...

The issue with Angular routing lies in the component content not displaying as expected

To showcase my project, I've created a demo on StackBlitz. I successfully implemented routing in my Angular application. You can find the code on StackBlitz. The sample consists of two components: AppComponent LoginComponent By default, when the ...

Can the functionality of ngIf and async pipe be replicated within the component's code?

With a form component and a thank you page, I am faced with the challenge of sharing data between these two components using rxjs ReplaySubject. The full code listings can be found here. In my implementation, I am utilizing ngIf and the async pipe to hand ...