How to display Images that are in a ts table

Viewed 383

I am trying to display from html file images that are in a table in .ts.

Here is my table:

BHs = [
  new Bh (1, "src/assets/img/photo_bonhommes/BH1.jpg"),
  new Bh (2, "src/assets/img/photo_bonhommes/BH2.png"),
  new Bh (3, "src/assets/img/photo_bonhommes/BH3.png"),
  new Bh (4, "src/assets/img/photo_bonhommes/BH4.png"),
  new Bh (5, "src/assets/img/photo_bonhommes/BH5.png"),
  new Bh (6, "src/assets/img/photo_bonhommes/BH6.png"),
  new Bh (7, "src/assets/img/photo_bonhommes/BH7.png"),
  new Bh (8, "src/assets/img/photo_bonhommes/BH8.png"),
  new Bh (9, "src/assets/img/photo_bonhommes/BH9.png"),
  new Bh (10, "src/assets/img/photo_bonhommes/BH10.png"),
  new Bh (11, "src/assets/img/photo_bonhommes/BH11.png"),
];

With the class :

 export class Bh {
  constructor(
    id: number,
    src: String,
  ){}
 }

And here is my html line :

<img id="bh" routerLink="/" *ngFor="let bh of BHs" src="bh.src"/> 
{{bh.src}}

I've seen people with the same problem, so I tried :

<img id="bh" routerLink="/" *ngFor="let bh of BHs" src="bh.src"/>

<img id="bh" routerLink="/" *ngFor="let bh of BHs" src="{bh.src}"/>

<div *ngFor="let bh of BHs">
    <img id="bh" routerLink="/" [src]='bh.src'/>
</div>

But none worked..

So I am a bit lost, I could use some help?

Thank you very much !

4 Answers

The problem isn't with the image binding, your class isn't defined properly, in your code if you simply console.log(BHs), you will get empty objects with no data, therefore bh.src is undefined

Declare your class like this:

 export class Bh {
  constructor(
    id: number,
    src: String,
  ){
      Object.assign(this, {id:id, src:src});
   }
 }

Working Demo

You have to use syntax like this -

<img id="bh" routerLink="/" *ngFor="let bh of BHs" [src]="bh?.src" />

I think you should use DomSanitizer;

import { DomSanitizer } from '@angular/platform-browser';  
  constructor(private sanitizer: DomSanitizer){

    this.imgSrc = this.sanitizer.bypassSecurityTrustResourceUrl(yourSrc);
}

When you pass this element :

new Bh (1, "src/assets/img/photo_bonhommes/BH1.jpg"), etc…

and then you call it in your template, is like doing this :

<img id="bh" routerLink="/" *ngFor="let bh of BHs" src="src/assets/img/photo_bonhommes/BH1.jpg"/> 

So maybe you should remove the excessive src and just put /assets/img/photo_bonhommes/….jpg

You can try this:

<img [id]="bh.id" routerLink="/" *ngFor="let bh of BHs" [src]="bh.src"/>
Related