Friday, October 24, 2025
HomeLanguagesJavascriptHow to display images in Angular2 ?

How to display images in Angular2 ?

We can serve an image in angular2 by first placing the image in the assets directory of your project where you can create a specific directory for the images or just keep it in the assets directory as it is.
Once you have put all the required images in the assets directory open the specific component typescript (.ts) file where you want to serve the image. Now you can add the URL of the image in a variable within the constructor so that it is initialized upon component creation.

Example
Demo.Component.ts




import { Component, OnInit } from '@angular/core';
  
@Component({
  selector: 'app-demo',
  templateUrl: './demo.component.html',
  styleUrls: ['./demo.component.css']
})
  
export class DemoComponent implements OnInit {
  ImagePath: string;
  
  constructor() {
    //image location
    this.ImagePath = '/assets/images/sample.jpg'
  }
  
  ngOnInit() {
  }
  
}


Now modify the component’s template file to fetch the image.
Demo.Component.html




<!--...header and body content-->
  
<mat-card class="example-card" >
  <mat-card-header class="example-header" 
                   style="padding-left: 40%;">
   <h2><span></span>neveropen</h2  >
  </mat-card-header>
  <mat-card-content>
    <img [src] ="ImagePath" 
          style="width: 600px;height: 400px;">
  </mat-card-content>
</mat-card>
  
<!--... body and footer content-->


Output: Output image

You can also fetch a web image directly from the website or database(For Ex. Firebase) by providing the full valid URL of the image.

NOTE:
In angular2, images and other media are by default fetched from the assets directory within your project folder(all other directories of the project are not public to the components by default) this can be changed by modifying angular-cli.json.Within this JSON file add your media directory by adding it in the assets object property.




//add a new directory or image to start fetching from that location
  
"assets": [
 "assets",
 "img",
 "favicon.ico",
 ".htaccess"
]


Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS