How can we set the url of the img element to print

2019-09-14 16:57发布

问题:

The assets folder consists of many images which are to be printed in the view according to the list elements. My code:

<ion-content padding>
  <ion-list>
    <ion-item *ngFor="let data of datas | async" class="pqr">
      <ion-thumbnail item-left>
        <img src= {{"../assets/image/" + data.imageName}}>
      </ion-thumbnail>
      {{data.Comp}}<br> 
      {{data.Demand}}<br>
      <p> {{data.Desig}}<br></p>
        {{data.Place}}<br>
        {{data.when}}<br>
    </ion-item>
  </ion-list>

</ion-content>

回答1:

You need to use the DomSanitizer.

// Angular
import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

...

@Component({...})
export class YourPage {

    constructor(private domSanitizer: DomSanitizer, ...) { 

        //...
    }

    public getImageUrl(data: any): any {
        let url = `../assets/image/${data.imageName}`;
        return this.domSanitizer.bypassSecurityTrustResourceUrl(url); 
    }
}

And then in your view:

<!-- ... -->
<ion-item *ngFor="let data of datas | async" class="pqr">
    <ion-thumbnail item-left>
        <img *ngIf="data && data.imageName" [src]="getImageUrl(data)">
    </ion-thumbnail>
<!-- ... -->