I am trying to display an image inside an ngFor loop like this :
HTML
<div *ngFor="let leg of flight.route">
<img [src]="getImage(leg.airline) | async" />
</div>
TS
getImage(airlineCode: string): Observable<any> {
return this.companyLogoService.getLogo(airlineCode);
}
This doesn't work. When this gets executed, all the requests to getImage()
seem to interrupt each other and loop infinitely :
According to similar threads, a way to handle this is to manually create a template variable holding the observable and then to pass this variable to the [src]
tag, but I can't afford to to that because of the ngFor loop.
How can I bind this image source properly ?
EDIT:
The requests to getImage()
were not interrupting each other. This behavior was caused by Angular change detection who went crazy because I directly mapped a function call to [src]
, which is not supported. The same problem happened with a single image to load.
Since there is apparently no such way to make this binding happen, I used an array to hold my observables, and I mapped them by index in my template.
TS
@Component({
selector: 'flight-card',
templateUrl: './flight-card.component.html',
styleUrls: ['./flight-card.component.scss']
})
export class FlightCardComponent implements OnInit {
@Input()
public flight: Flight;
public airlineImages: Observable<any>[];
constructor(private companyLogoService: CompanyLogoService) {
}
ngOnInit() {
this.airlineImages = [];
this.flight.route.forEach(leg => {
this.airlineImages.push(this.companyLogoService.getLogo(leg.airline));
});
}
}
HTML
<div *ngFor="let leg of flight.route; let i = index">
<img [src]="this.airlineImages[i] | async" />
</div>