Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: ternary operation for img src attribute?

My data has a property "photo", which may be empty or contain a file name.

For example, "steve.jpg" or "" if steve has no photo.

In React JSX I could use a ternary operator on the value of "photo", but I don't know how to do it with Angular 8.

In know I could use 2 image tags with 2 ngIfs, but I'd like ot make it more dry. This doesn't work for me at all:

<img[attr.src]="person.photo !=='' ? '/assets/images/people/{{person.photo}}' : '/assets/images/people/missing-person.jpg'">
like image 390
Steve Avatar asked Feb 07 '26 09:02

Steve


1 Answers

it's just [src] in angular, and the {{ }} syntax isn't valid in bindings. Only in interpolation, just access the variables like normal

<img [src]="person.photo !=='' ? '/assets/images/people/' + person.photo : '/assets/images/people/missing-person.jpg'">
like image 65
bryan60 Avatar answered Feb 09 '26 00:02

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!