How to load an image in Angular with examples

This tutorial shows multiple examples in Angular, One example is to load images using the img tag Another example is to bind the src attribute to the assets folder.

Angular Img tag binding

Normally, Images are placed in the src/assets folder in the Angular application.

src
|__assets
   |__images
      |__first.png
|__app
   |__app.component.html

The Img tag is used to display an image on an angular application.

It is declared in the HTML template file.

<img src="path" alt="text" />

src contains the absolute path of images that referred from the HTML file alt contains string content to display on the image for SEO purposes

to bind a path and alt from a typescript component, use binding square syntax.

Declare a variable of a string

path: string = "../assests/images/first.png";
alttext: string = "first image";

display in HTML template with expression syntax

<img [src]="path" [alt]="alttext" />

[src]=path is binding to typescript component variable path or you can use the variable directly using {{}} syntax without binding

<img src="{{path}}" alt="{{alttext}}" />

Image does not show in Angular

Please follow the below steps

  • If images do not display correctly, check src/assets folder included inside the assets attribute in the angular.json file of angular application.
{
  "assets": ["src/favicon.ico", "src/assets"]
}
  • Check path relevant HTML file location with the assets folder
  • Check image binding is correctly done