繁体   English   中英

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

[英]How to set background image in angular 6?

在这里我想设置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')";
}

共class.ts

export class CommonClass {
  constructor(public commonUrl : string = 'http://localhost:3000'){};
}
getUrl(){
  return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
}

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

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

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

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

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

根据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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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