Skip to main content

Implementing Image Handling

1. Using IonImg Component

Property Values Description
src string URL or path to the image resource
alt string Alternative text for accessibility
loading 'lazy' | 'eager' Controls when the image is loaded
disabled boolean Disables the component if true

Example: Basic Usage of IonImg

<ion-img src="https://example.com/image.jpg" alt="Example Image"></ion-img>

Example: Lazy Loading Image

<ion-img src="/assets/images/photo.png" loading="lazy"></ion-img>
Note: The IonImg component provides built-in lazy loading and error handling for images.

2. Configuring Image Source

Property Values Description
src string URL or path to the image resource
alt string Alternative text for accessibility
loading lazy | eager Lazy loading strategy for image
width number | string Width of the image in pixels or CSS units
height number | string Height of the image in pixels or CSS units

Example: Setting Image Source

<ion-img src="https://example.com/image.jpg" alt="Example Image"></ion-img>

Example: Lazy Loading Image

<ion-img src="/assets/images/photo.png" loading="lazy"></ion-img>

3. Handling Image Load Events

Event Description Usage
ionImgDidLoad Fires when an image has successfully loaded. <ion-img [src]="'/assets/image.jpg'" (ionImgDidLoad)="onImageLoad()"></ion-img>
ionImgError Fires when an image fails to load. <ion-img [src]="'/assets/image.jpg'" (ionImgError)="onImageError()"></ion-img>
Note: These events are specific to the <ion-img> component and provide better control over image loading than standard HTML events.

4. Implementing Placeholder Images

Property Description Usage
ion-img Component for lazy-loading images with placeholders <ion-img [src]="'/assets/imgs/photo.jpg'" [placeholder]="'/assets/imgs/placeholder.jpg'"></ion-img>
src URL of the image to load <ion-img [src]="'/assets/imgs/photo.jpg'"></ion-img>
placeholder URL of the placeholder image to show while loading <ion-img [src]="'/assets/imgs/photo.jpg'" [placeholder]="'/assets/imgs/placeholder.jpg'"></ion-img>

Example: Using ion-img with Placeholder

<ion-img [src]="'/assets/imgs/photo.jpg'" [placeholder]="'/assets/imgs/placeholder.jpg'"></ion-img>
Note: The ion-img component is optimized for lazy loading and supports placeholders to improve perceived performance.

Key Features

  • Lazy loading of images to improve performance
  • Supports placeholder images during load
  • Automatic handling of image dimensions

5. Using Responsive Images

Property Description Values
src Source URL of the image <string>
alt Alternative text for accessibility <string>
width Width of the image in pixels <number>
height Height of the image in pixels <number>
loading Lazy loading strategy "lazy", "eager"
sizes Image size for different viewports <string>
srcset Image set for different resolutions <string>

Example: Basic Responsive Image

<img src="image.jpg" alt="Example image" width="300" height="200">

Example: Image with srcset and sizes

<img src="image.jpg"
     srcset="image-320w.jpg 320w,
              image-480w.jpg 480w,
              image-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
              (max-width: 480px) 440px,
              800px"
     alt="Example image with responsive sizes">
Note: Use srcset and sizes to provide multiple image sizes for different screen resolutions and viewports.

6. Optimizing Image Loading

Property Description Values Notes
ion-img Component for lazy loading images <ion-img> Improves performance by deferring load until in viewport
src Image source URL or path string Supports local and remote image URLs
alt Alternative text for accessibility string Required for screen readers and SEO
loading Lazy loading behavior "lazy" | "eager" Default is "lazy", improves initial load

Example: Using ion-img for lazy loading

<ion-img src="assets/images/photo.jpg" alt="A scenic view"></ion-img>

Example: Preloading critical images

<ion-img src="assets/images/logo.png" loading="eager" alt="App logo"></ion-img>
Note: Use ion-img instead of standard HTML <img> for better performance in Ionic apps.
Feature Description Support
Lazy Loading Images load only when they enter the viewport Supported
Preload Strategy Option to eagerly load images Supported
Fallback Image Display placeholder while image loads Supported

Optimization Workflow

  1. Identify images that are not immediately visible on screen
  2. Replace standard <img> tags with <ion-img>
  3. Set appropriate loading attribute for performance
  4. Use alt tags for accessibility
  5. Implement fallback or placeholder images where needed

7. Displaying Image Errors

Property Description Default Notes
errorSrc URL of the fallback image to display when the primary image fails to load. null Used in conjunction with src to handle image loading failures gracefully.
errorHandler Function to handle image loading errors and customize error behavior. null Allows developers to implement custom logic for error handling or logging.

Example: Using errorSrc for Fallback Image

<ion-img [src]="imageUrl" [errorSrc]="fallback.png"></ion-img>

Example: Custom Error Handling with errorHandler

const handleError = () => {
  console.log("Image failed to load");
  // Implement custom logic here
};
Note: The errorSrc property is particularly useful for improving UX in mobile apps where network conditions may vary.

8. Creating Image Galleries

import { Component } from '@angular/core';

@Component({
  selector: 'app-image-gallery',
  template: &#x27;<ion-grid>
  <ion-row>
    <ion-col size="6" *ngFor="let image of images">
      <ion-img [src]="image.src" [alt]="image.alt"></ion-img>
    </ion-col>
  </ion-row>
</ion-grid>&#x27;
})
export class ImageGalleryComponent {
  images = [
    { src: &#x27;assets/images/image1.jpg&#x27;, alt: &#x27;First image&#x27; },
    { src: &#x27;assets/images/image2.jpg&#x27;, alt: &#x27;Second image&#x27; },
    { src: &#x27;assets/images/image3.jpg&#x27;, alt: &#x27;Third image&#x27; },
    { src: &#x27;assets/images/image4.jpg&#x27;, alt: &#x27;Fourth image&#x27; }
  ];
}
Property Description Default
src URL or path to the image resource None
alt Alternative text for accessibility Empty string
loading Controls loading behavior (e.g., 'lazy') 'eager'
Note: Use ion-img instead of native <img> for better performance and lazy loading support in Ionic apps.
<ion-grid>
  <ion-row>
    <ion-col size="12">
      <ion-img [src]="mainImage.src" [alt]="mainImage.alt"></ion-img>
    </ion-col>
  </ion-row>
  <ion-row>
    <ion-col size="3" *ngFor="let thumb of thumbnails">
      <ion-img [src]="thumb.src" [alt]="thumb.alt" (click)="setMainImage(thumb)"></ion-img>
    </ion-col>
  </ion-row>
</ion-grid>
  • Use ion-img for optimized image loading
  • Implement lazy loading for better performance
  • Provide alternative text (alt) for accessibility
  • Ensure responsive layout using ion-grid
  • Consider image compression and appropriate formats (e.g., WebP)

9. Implementing Image Zoom

Example: Basic Image Zoom with Ionic & Hammer.js

import { Component, ViewChild } from '@angular/core';
import { IonImg } from '@ionic/angular';
import { Hammer } from 'hammerjs';

@Component({
  selector: 'app-image-zoom',
  template: &#x27;<ion-img #img [src]&#x3D;"imageUrl" (ionImgDidLoad)&#x3D;"onImageLoad(img)"></ion-img>&#x27;
})
export class ImageZoomComponent {
  @ViewChild(&#x27;img&#x27;) img: IonImg;
  imageUrl = &#x27;https://example.com/image.jpg&#x27;;

  onImageLoad(img: IonImg) {
    const hammer = new Hammer(img.el);
    hammer.get(&#x27;pinch&#x27;).set({ enable: true });
    hammer.get(&#x27;pan&#x27;).set({ enable: true });

    let scale = 1;
    let posX = 0;
    let posY = 0;

    hammer.on(&#x27;pinchstart&#x27;, () => {
      scale = 1;
    });

    hammer.on(&#x27;pinch&#x27;, (ev) => {
      scale = Math.min(Math.max(0.5, ev.scale), 3);
      img.el.style.transform = `scale(${scale}) translate(${posX}px, ${posY}px)`;
    });

    hammer.on(&#x27;pan&#x27;, (ev) => {
      posX += ev.deltaX;
      posY += ev.deltaY;
      img.el.style.transform = `scale(${scale}) translate(${posX}px, ${posY}px)`;
    });
  }
}
Feature Description Notes
ion-img <ion-img> component for optimized image loading Supports lazy loading and error handling
Hammer.js Touch gesture library for pinch/pan support Used to detect zoom and pan gestures
scale Zoom level multiplier (1 = normal) Range: 0.5 to 3
transform CSS transform property for scaling and panning Applied to ion-img element
Note: Requires hammerjs to be installed and imported in your project.
Warning: Zooming may cause performance issues with large images or on low-end devices.

10. Using Avatar and Thumbnail

Property Description Default Notes
src Image source URL or path null Required for display
alt Alternative text for accessibility "" Recommended for screen readers
mode Component mode (ios or md) md Applies platform-specific styling

Example: Avatar with fallback

<ion-avatar>
  <img src="https://example.com/avatar.jpg" alt="User avatar">
</ion-avatar>

Example: Thumbnail with error handling

<ion-thumbnail>
  <img src="https://example.com/thumb.jpg" alt="Thumbnail image">
</ion-thumbnail>
Note: Use alt attribute for accessibility compliance.
Warning: Ensure image URLs are valid to prevent broken image displays.

Was this article helpful?