mohammed fahimullah
mohammed fahimullah

Reputation: 649

Angular ngSrc doesnt accept dynamic value

    <ng-container *ngFor="let image of images">
    <img [ngSrc]="'assets/images/' + image" alt="My Image">
  </ng-container>

   public images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];

I have the above code. I want to pass dynamic value to the ngSrc attribute but it doesn't work. Am I doing something wrong ?

Upvotes: 1

Views: 74

Answers (1)

Naren Murali
Naren Murali

Reputation: 56650

You are missing to specify the height and width property which is causing this issue.

<img [ngSrc]="'/assets/images/' + image" alt="My Image" width="600" height="400">

You can also specify fill, when fill is used there is no need for height and width.

<img [ngSrc]="'/assets/images/' + images[0]" fill>

Getting started with NgOptimizedImage - Angular Documentation

Full Code:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { NgOptimizedImage } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, NgOptimizedImage],
  template: `
    <ng-container *ngFor="let image of images">
      <img [ngSrc]="'/assets/images/' + image" alt="My Image" width="600" height="400">
    </ng-container>
  `,
})
export class App {
  public images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
}

bootstrapApplication(App);

Stackblitz Demo

Upvotes: 0

Related Questions