<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 ?
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>
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);