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 ?
To bind the src property of an <img> element to a component's property, place the target, src , in square brackets followed by an equal sign and then the property.
Property binding is the base method of binding in Angular, it involves binding values to DOM properties of HTML elements. It is a one-way binding method, as values go from the component to the template layer and changes made in the component updates the properties bound in the template.
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>
I hope i am understanding your question correctly, as the above comment says you need to provide more information.
In order to bind it to your view you would use property binding which is using [property]="value". Hope this helps.
<div *ngFor="let student of students">
{{student.id}}
{{student.name}}
<img [src]="student.image">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With