如何在角度6中设置背景图像?

时间:2018-10-23 08:12:55

标签: html css angular angular6

这里我想设置placehoder图像,为此我使用commonurl路径(this.commonUrlObj.commonUrl)而不是({http://localhost:3000),因此如何在角度6中使用commonurl设置背景图像中的图像?

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'){};
}

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

也许我不明白您的问题,但这是您想做的吗?

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

答案 2 :(得分:0)

您不能为图片添加背景图片。您可以做的是包装div并为其提供背景:

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

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

答案 3 :(得分:0)

根据Angular.io中的文档,您可以为ngStyle提供一个ObjExp。这样。

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>
相关问题