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">
[src]="item.pictureUrl!= null ? item.pictureUrl : myImgUrl"
then in your .ts
export class App{
myImgUrl:string='~/images/logo.png';
}
[src]="item.pictureUrl ? item.pictureUrl : 'assets/img/logo.png'"
Maybe better way is to keep your images in assets folder: assets/img/logo.png
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}`;
}
}
<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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With