admin管理员组

文章数量:1300042

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'">

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'">
Share Improve this question asked Jul 31, 2019 at 14:57 SteveSteve 14.9k37 gold badges138 silver badges245 bronze badges 1
  • Have you tried to do this without the attr. ? – Morphyish Commented Jul 31, 2019 at 14:59
Add a ment  | 

2 Answers 2

Reset to default 8

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'">

You can do it like :

<img src="/assets/images/people/{{ (person.photo !=='' ? person.photo : 'missing-person') + '.jpg'}}">

本文标签: javascriptAngular 8 ternary operation for img src attributeStack Overflow