Angular associate json value to img path

Viewed 30

I have to display data that comes from an api that works well, I need to display each country with its corresponding flag but I don't understand how to associate the value of a json with the path of an image.

example : for the

libelle: Cambodge bigramme: KH

display: src/assets/flags/KH.jpg


libelle: France bigramme: FR

display: src/assets/flags/FR.jpg

I have tried to be as clear as possible.

thank you.

json

"drapeaux": [
    {
      "id": 1,
      "mnemo": "KHM",
      "libelle": "Cambodge",
      "bigramme": "KH"
    },
    {
      "id": 2,
      "mnemo": "KHM",
      "libelle": "France",
      "bigramme": "FR"
    }
  ]
}

service

getAll(): Observable<Ipost[]> {
    return this.http.get<Ipost[]>(this.api);
  }

components.ts

 getAllNations() {
    let resp = this.homeService.getAll();
    resp.subscribe(result => {
      this.postArray = result;
    });
  }

html

<div class="col-12">
      <mat-card>
        <div class="row">
          <div class="col-1" *ngFor="let post of postArray">
            {{post.libelle}}
            <img [src]="post.bigramme.jpg" alt="flag">
          </div>
        </div>
      </mat-card>
    </div>
1 Answers

You have two options:

Option 1: In your service:

getAll(): Observable<Ipost[]> {
  return this.http.get<Ipost[]>(this.api).pipe(
    map(p => ({
      ...p,
      bigramme: `src/assets/flags/${p.bigramme}.jpg`
    }))
  )
}

And then your Component's html:

<div class="col-12">
  <mat-card>
    <div class="row">
      <div class="col-1" *ngFor="let post of postArray">
        {{post.libelle}}
        <img [src]="post.bigramme" alt="flag">
      </div>
    </div>
  </mat-card>
</div>

Option 2: Or you can change only your Component's html:

<div class="col-12">
  <mat-card>
    <div class="row">
      <div class="col-1" *ngFor="let post of postArray">
        {{post.libelle}}
        <img src="src/assets/flags/{{ post.bigramme }}.jpg" alt="flag">
      </div>
    </div>
  </mat-card>
</div>
Related