简体   繁体   中英

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'){};
}
getUrl(){
  return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}

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

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

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM