Src conditional image binding in angular 2

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

Below is the code I tried, but this does not work.

 <img class="lib-img" [src]="item.pictureUrl!= null ? item.pictureUrl : ~/images/logo.png" height="500" width="500" alt="default image"> 
+13
source share
4 answers
 [src]="item.pictureUrl!= null ? item.pictureUrl : myImgUrl" 

then in your .ts

 export class App{ myImgUrl:string='~/images/logo.png'; } 
+21
source
 [src]="item.pictureUrl ? item.pictureUrl : 'assets/img/logo.png'" 

Perhaps the best way to save your images in the assets folder is: assets / img / logo.png

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

It will do the trick

For more binding information, follow this link.

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

0
source

.html

 [src]="validateURL(item.pictureUrl)" 

.ts

 validateURL(url) { let valid = /^(https?|s?ftp):\/\/(((([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([az]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([az]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([az]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url); if (valid) return url; else return '';// or "link/to/image1.png" } 
0
source

Source: https://habr.com/ru/post/1263533/


All Articles