how to bind img src in angular 2 in ngFor?
In my project I am getting data: image src, student name and student id. I bind student name and student id.
How to bind image src in angular 2 ?
Angular 2, 4 and Angular 5 compatible!
You have provided so few details, so I'll try to answer your question without them.
You can use Interpolation:
<img src={{imagePath}} />
Or you can use a template expression:
<img [src]="imagePath" />
In a ngFor
loop it might look like this:
<div *ngFor="let student of students">
<img src={{student.ImagePath}} />
</div>
Angular 2.x to 8 Compatible!
You can directly give the source property of the current object in the img src attribute. Please see my code below:
<div *ngFor="let brochure of brochureList">
<img class="brochure-poster" [src]="brochure.imageUrl" />
</div>
NOTE: You can as well use string interpolation but that is not a legit way to do it. Property binding was created for this very purpose hence better use this.
NOT RECOMMENDED :
<img class="brochure-poster" src="{{brochure.imageUrl}}"/>
Its because that defeats the purpose of property binding. It is more meaningful to use that for setting the properties. {{}} is a normal string interpolation expression, that does not reveal to anyone reading the code that it makes special meaning. Using [] makes it easily to spot the properties that are set dynamically.
Here is my brochureList contains the following json received from service(you can assign it to any variable):
[ {
"productId":1,
"productName":"Beauty Products",
"productCode": "XXXXXX",
"description": "Skin Care",
"imageUrl":"app/Images/c1.jpg"
},
{
"productId":2,
"productName":"Samsung Galaxy J5",
"productCode": "MOB-124",
"description": "8GB, Gold",
"imageUrl":"app/Images/c8.jpg"
}]
Angular 2 and Angular 4
In a ngFor loop it must be look like this:
<div class="column" *ngFor="let u of events ">
<div class="thumb">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
</div>
<div class="info">
<img src="assets/uploads/{{u.image}}">
<h4>{{u.name}}</h4>
<p>{{u.text}}</p>
</div>
</div>