Lucifer
Lucifer

Reputation: 842

Change img [src] dynamically

I have component which have list of records

export class HomeComponent implements OnInit {

    public wonders: WonderModel[] = [];

    constructor(private ms: ModelService){
        ms.wonderService.getWonders();
        this.wonders = ms.wonderService.wonderList;
    }

    ngOnInit(){}
}

this.wonders returns array of values like this array of this.wonders

I am trying to get that id value to image source dynamically like this

<div class="img-content" *ngFor="let wonder of wonders">
    <header class="img-content-header">
        <div style="width: 45px; display: table-cell;"> <img [src]='assets/images/{{wonder.id}}.jpg'  height="40px" width="40px"> </div>
        <div style="display: table-cell;">
            <div>{{wonder.name}}</div>
        </div>
    </header>
</div>

While doing so I am getting this error

Parser Error: Got interpolation ({{}}) where expression was expected at column 14 in [assets/images/{{wonder.id}}.jpg]

Can anyone suggest any possible solution for that.

Upvotes: 33

Views: 103076

Answers (4)

Mauro Doza
Mauro Doza

Reputation: 341

You are using interpolation and property binding in the section

[src]='assets/images/{{wonder.id}}.jpg'

You could either remove the property binding

src='assets/images/{{wonder.id}}.jpg'

or remove the interpolation

[src]='assets/images/' + wonder.id + '.jpg'

For more information check out Property Binding or Interpolation in Angular

Upvotes: 16

Suren Srapyan
Suren Srapyan

Reputation: 68665

You need to bind like this

<img src='{{ "assets/images/" + wonder.id + ".jpg" }}'

[] is not compatible with {{ }}.

Upvotes: 42

Pranay Rana
Pranay Rana

Reputation: 176906

its interpolation , so you dont need [] that is needed when you create full path from the back-end typescript and assign it , so just removing [] will work for you

<img src='assets/images/{{wonder.id}}.jpg'  height="40px" width="40px">

[] is helpful when you are binding full vaule which so coming from typescript, example

<img [src]='path'  height="40px" width="40px"> 

in type script you are having path variable

 const path = 'imagepath.jpg';

Upvotes: 5

Vivek Doshi
Vivek Doshi

Reputation: 58573

You can do it like :

[src]='"assets/images/"+wonder.id+".jpg"'

OR

src='assets/images/{{wonder.id}}.jpg'

Upvotes: 31

Related Questions