Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Image Src Binding in angular 2

Tags:

angular

How to write the ternany condition for <img> src in Angular 2.

Below is the code I tried but this is not working

<img class="lib-img" [src]="item.pictureUrl!= null ? item.pictureUrl : ~/images/logo.png" height="500" width="500" alt="default image">
like image 822
San Jaisy Avatar asked Jan 29 '17 08:01

San Jaisy


4 Answers

[src]="item.pictureUrl!= null ? item.pictureUrl : myImgUrl"

then in your .ts

export class App{
   myImgUrl:string='~/images/logo.png';
}
like image 176
Nikhil Shah Avatar answered Oct 13 '22 03:10

Nikhil Shah


[src]="item.pictureUrl ? item.pictureUrl : 'assets/img/logo.png'"

Maybe better way is to keep your images in assets folder: assets/img/logo.png

like image 26
Admir Avatar answered Oct 13 '22 03:10

Admir


If you want to use variable in image #svg to get source svg.getAttribute('src'), you need implement method to get image in ts file instead of if else in html file.

I shared for whom concerned.

<div *ngFor="let widget of svgFiles" class="listItem">
    <a draggable="true" class="nav-link" (dragstart)="onDrag($event, 14, svg.getAttribute('src'))">
        <img [src]="getImage(widget)" #svg />                           
    </a>
    <p>{{widget.Name}}</p>
</div>

TS file

getImage(widget) {
        if (this.isRootSearch) {
            return `./assets/svg${widget}`;
        } else {
            return `./assets/svg/${this.selectedSVGFolder}/${widget}`;
        }
    }
like image 4
Hien Nguyen Avatar answered Oct 13 '22 01:10

Hien Nguyen


<img [src]="item.pictureUrl!= null ? 'link/to/image1.png' : 
'link/to/image2.png'"> 

This will do the trick

For more binding information follow this link

https://angular.io/guide/template-syntax#html-attribute-vs-dom-property

like image 3
Shameer Avatar answered Oct 13 '22 03:10

Shameer