Search code examples
angularkendo-ui-angular2kendo-ui-grid

Kendo UI grid - how to display an image in ng-template


Essentially we have a images which exists in the ./assets folder of our web server.

The logic is: display the patient image in the grid if it exists, otherwise render the default image 0.jpg.

Here's my Kendo UI grid column to show the patient image - IF IT EXISTS:

<kendo-grid-column>
  <ng-template kendoGridCellTemplate let-dataItem>                                  
    <img *ngIf="'./assets/profiles/patients/' + dataItem.PatientID + '.jpg'" src="{{ './assets/profiles/patients/' + dataItem.PatientID + '.jpg'}}" height="40" width="40" style="border-radius:30px;" alt="Patient Image"/>
 </ng-template>
</kendo-grid-column>

Here's an idea to combine the logic, render either patient image or the default image:

<kendo-grid-column>
	<ng-template kendoGridCellTemplate let-dataItem>
		<img src="{{ './assets/profiles/patients/' + dataItem.PatientID + '.jpg' ? './assets/profiles/patients/' + dataItem.PatientID + '.jpg' :  defPatientImage}}" 
			height="40" width="40" style="border-radius:30px;" alt="Patient Image"/>
	</ng-template>
 </kendo-grid-column>

Problem (in both examples) is that it ALWAYS attempts to display the patient image.

So of course I get console errors something like this :

 GET http://localhost:4200/assets/profiles/patients/789456.jpg 404 (Not Found)

NOTE: I don't have the image path data in my grid data set. For now I have to go straight to the assets folder (this is a prototype).

Any idea what's wrong with my ngIf statement ?

thanks.


Solution

  • I didn't realize how simple the solution really was. I just needed the onerror event on the img tag itself.

     <kendo-grid-column>
        <ng-template kendoGridCellTemplate let-dataItem>
            <img src="{{ './assets/profiles/patients/' + dataItem.PatientID + '.jpg' }}" 
                    onerror=" this.src = './assets/profiles/patients/0.jpg' "
                    height="40" width="40" style="border-radius:30px;" alt="Patient Image"/>                    
            </ng-template>
     </kendo-grid-column>