Dharmesh
Dharmesh

Reputation: 6003

How to set background image in angular 6?

Here i want to set placehoder image and for that i use commonurl path (this.commonUrlObj.commonUrl) instead of (http://localhost:3000) so how to set image in background-image using commonurl in angular 6?

category.component.html

<img [src]="url" style="height: 400px;width: 400px" [ngStyle]="{'background-image': getUrl()}">

category.component.ts

getUrl(){
  return "url('this.commonUrlObj.commonUrl/placeholder.jpg')";
}

common-class.ts

export class CommonClass {
  constructor(public commonUrl : string = 'http://localhost:3000'){};
}

Upvotes: 0

Views: 4995

Answers (4)

T04435
T04435

Reputation: 13992

As per docs in Angular.io you can give ngStyle an ObjExp. Like this.

TS
// Not in the question but don't use a constructor to define vars
private commonUrl: string = 'localhost:3000'; // Could have this as an env variable

getBackground() {
   return {'background-image': `url(${this.commonUrl}/placeholder.png)`};
}

HTML
<div [ngStyle]="getBackground()"></div>

Upvotes: 0

Ikhlak S.
Ikhlak S.

Reputation: 9024

You can't have an background image for an image. What you can do is wrap a div and give it an background:

getUrl(){
  return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}

<div  [ngStyle]="{'background-image': getUrl()}>
  <img [src]="url" style="height: 400px;width: 400px">
</div>

Upvotes: 0

Kevin ALBRECHT
Kevin ALBRECHT

Reputation: 524

Maybe I didn't understand your problem but is this what you wanted to do ?

getUrl(){
  return `url('${this.commonUrlObj.commonUrl}/placeholder.jpg')`;
}

Upvotes: 1

Charlie Rabiller
Charlie Rabiller

Reputation: 512

getUrl(){
  return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}

Upvotes: 3

Related Questions