0

In my angular 4 project I have to load some thumbnails, I have thumbnail form many type of things like pdf, image, documents etc.

My code to load image is:

 <div class="card-image">
      <img class="img" src="{{pic.selfLink}}/thumbnail?width={{width}}">
  </div>

But obviously if there aren't any thumbnails I have to load some default image, this default image needs to be different based on the extension of the file.

How can I achieve that?

Image

Alessandro Celeghin
  • 4,039
  • 14
  • 49
  • 95

2 Answers2

0

Create a method to return the defult image based on the extension.

HTML:

This is called if data is not there

<div class="card-image">
      <img class="img" *ngIf="!pic.image" src="getDefaultImage(pic.extension)">
  </div>

In component:

Return the image based on extension

public getDefaultImage(extension) {
    let defaultImage = '';
    switch (extension) {
    case 'img':
        defaultImage = "something";
        break;
    case 'txt':
        defaultImage = "something";
        break;
    case 'pdf':
        defaultImage = "something";
        break;
  }
  return defaultImage;
}
Sravan
  • 18,467
  • 3
  • 30
  • 54
0

You can bind the image source to a function in your component class.

<img [src]="getImageSource()">

In your component.ts file

  getImageSource() {
    const imageSource: String;
    if (pic.selfLink) {
      imageSource = `${this.pic.selfLink}/thumbnail?width=${this.width}`;
    } else {
      imageSource = 'Path to your alt image';
    }
  }
Ankit Kapoor
  • 1,615
  • 12
  • 18
  • pic.selfLink is a variable that contains always a link to the image, only server knows if the image exists or not – Alessandro Celeghin Nov 20 '17 at 11:01
  • You can use a http service which will hit this link and based on that response status (200 or 400/404) you can decide your image. – Ankit Kapoor Nov 20 '17 at 11:05
  • But if I use a function to make a http get and this function returns a link to the image, the image i loaded in the component and in the html? – Alessandro Celeghin Nov 20 '17 at 11:15
  • What I can understand from your last comment is that you will create a function to which you will pass URL. Then this function will hit this link with via HTTP and on the basis of response it will return correct link (which could be alt image as well). Correct? – Ankit Kapoor Nov 20 '17 at 11:19
  • correct but now the tag image src make another GET call to the image, so I have double calls – Alessandro Celeghin Nov 20 '17 at 11:24
  • 1
    For this you can parse the data from http and use that data as image. And in image element instead of providing image link you can provide image data directly. See this link : https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4?answertab=active#tab-top – Ankit Kapoor Nov 20 '17 at 11:35