How do I Display Images From Another Origin in My Angular Web Application?


Using the Assets Directory

We can serve an image in angular by first placing it in our project's assets directory, where we can create a separate directory for images or simply leave it in the assets directory as is. We can open the specific component typescript (.ts) file where we want to serve the image once we have placed all of the required images in the assets directory. Now we can store the image's URL in a variable within the function Object() { [native code] } so that it is initialised when the component is created.

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_img.jpg'
  }
  ngOnInit() {
  }
}

To retrieve the image, we must now modify the component's template file.

Demo.Component.html

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

We can also get a web image directly from a website or database (for example, Firebase) by providing the image's full valid URL.

Images and other media are fetched by default in angular from the assets directory within your project folder (all other project directories are not public to the components by default), but this can be changed by modifying angular-cli.json. We can include our media directory in this JSON file by including it in the assets object property.

"assets": [
 "assets",
 "img",
 "favicon.ico",
 ".htaccess"
]

Using NgOptimizedImage

The NgOptimizedImage directive makes it simple to implement best practices for image loading performance. It prioritizes the loading of the Largest Contentful Paint image by:

  • Setting the fetchpriority attribute on the <img> tag automatically.

  • Ensuring that other images are loaded slowly by default.

  • Asserting that the document head contains a corresponding preconnect link tag.

NgOptimizedImage enforces a number of image best practices in addition to optimizing the loading of the LCP image:

  • Image optimization by using image URLs

  • It is necessary to specify the width and height.

  • Notifies you if the width or height have been set incorrectly.

  • If the image will be visually distorted when rendered, this function will notify you.

The directive must be imported into our application. We'll also need to set up an image loader.

To use the NgOptimizedImage directive in a template, we must replace the src attribute of our image with ngSrc.

<img ngSrc="sample_image.jpg" width="200" height="80">

The built-in third-party loaders prefix src with a shared base URL. To avoid unnecessary duplication, if we use one of these loaders (or any other loader that does this), we must remove the shared base URL path from src.

We must also specify the width and height. This is done to avoid image-related layout changes. The width and height attributes should reflect the image's inherent size. During development, the NgOptimizedImage warns if the width and height attributes are incorrectly set.

To ensure that the LCP image loads as quickly as possible, we can add a preconnect resource hint for your image origin. It is best to include resource hints in the document's <head>.

<link rel="preconnect" href="https://my.cdn.origin" />

If we use a loader for a third-party image service, the NgOptimizedImage directive will warn us during development if it detects that the origin that serves the LCP image does not have a preconnect resource hint. To disable these warnings, add ensurePreconnect: false to the provider factory arguments for our chosen image service:

providers: [
  provideImgixLoader('https://my.base.url', {ensurePreconnect: false})
],

Adding width and height attributes to an image may cause it to render differently depending on its styling. NgOptimizedImage will alert us if our image styling results in a distorted aspect ratio. This is usually remedied by adding height: auto or width: auto to your image styles.

We must replace the srcset attribute in our <img> tag with ngSrcset. If the ngSrcset attribute is present, NgOptimizedImage generates and sets the srcset attribute using the image loader that has been configured. The directive infers this information from ngSrc, so do not include image file names in ngSrcset. The directive accepts both width descriptors (for example, 100w) and density descriptors (for example, 1x).

Updated on: 12-Sep-2023

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements