簡體   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