Search code examples
angularangular-ng-if

How can I show a different image if the URL string end with **.pdf** in Angular?


I have the following problem working on an Angular application. Into my HTML code I have something like this:

<ng-template pTemplate="body" let-file>
    <tr>
      <td>
        <img class="img-thumbnail" src={{file.info.file_url}}/>
      </td>
      ............................................................
      ............................................................
      ............................................................

So as you can see I am using the img tag in order to show an image from an URL. The problem is that sometimes this URL is not an image but it could be a PDF file. In this case the image is not shown and I obtain something like this:

enter image description here

So what I want to di is:

I have put a PDF icon image into the /src/assets/img/pdf.png folder of my project. I want to check (if possible into the previous html code using something like *ngIf directive) if the file.info.file_url property value end with .pdf and in case use this /src/assets/img/pdf.png instead the value of the file.info.file_url property.

How can I achieve this task?


Solution

  • You could do something like

    function isPdf(file) {
      const extension = file.substr((file.lastIndexOf('.') +1));
      return /(pdf)$/ig.test(extension)
    }
    

    ...

      <td>
        <img class="img-thumbnail" src="{{isPdf(file.info.file_url) ? '/src/assets/img/pdf.png' : file.info.file_url}}" />
      </td>