1

I have a list which looks like this:

<ul *ngFor="#item of items">
<li><img src="http://something.com/[this needs to be item.id]/picture"></li>
</ul>

I need to the image url to be that of the id of the item. I looked at the src documentation for angular2 (https://angular.io/docs/ts/latest/guide/template-syntax.html) and tried the following:

<img [src]="http://something.com/{{item.id}}/picture">

but it did not work. How can I have the image show up based on the item's id which needs to be in the url.

1 Answer 1

6

Use property binding with string literals:

<img [src]="'http://something.com/' + item.id + '/picture'">

or string interpolation property binding with {{}}s:

<img src="http://something.com/{{item.id}}/picture">

Note that [src]="http://something.com/{{item.id}}/picture"> doesn't work because property binding with [] uses the syntax [property]="template_expression" and the template_expression can not contain {{}}s.

Sign up to request clarification or add additional context in comments.

7 Comments

I think 1st should appropriate, as like ng-src in Angular 1, where as 2nd one can form incorrect URL like http://something.com//picture, correct?
Thanks! It works! And thanks for explaining why my approach didn't work!
@PankajParkar, well, both forms will generate incorrect URLs if id is not a property of the item. The first will produce "http://something.com/undefined/picture" and the second, "http://something.com//picture".
@MarkRajcok correct.. even that could failed if you don't have Elvis operator in a place.. like item?.id
@PankajParkar, oh, okay, now I see your point. I believe both forms will result in invalid URL fetches if the id field is not populated when the view is rendered or updated.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.