Blog>
Snippets

Optimizing Images with Angular

Show how to use Angular's built-in directives to load appropriate image sizes for different screen resolutions to help reduce data usage on mobile.
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public getSrcSet(imageName: string): string {
    return `images/${imageName}-small.jpg 500w,
            images/${imageName}-medium.jpg 1000w,
            images/${imageName}-large.jpg 1500w`;
  }
}
This TypeScript code defines an Angular component and a method that constructs a srcset string used to specify different image files for various screen widths. '500w', '1000w', and '1500w' indicate the image widths.
app.component.html
<img [src]="'images/default-image-large.jpg'" [attr.srcset]="getSrcSet('your-image-name')" [alt]="'Descriptive text for the image'">
This HTML code uses Angular property binding to set the default image source and the srcset attribute generated by the getSrcSet method. The alt attribute provides alternative text if the image cannot be displayed.