【问题标题】:How to set background image in angular 6?如何在角度 6 中设置背景图像?
【发布时间】:2019-03-27 09:42:42
【问题描述】:

在这里我想设置占位符图像,为此我使用 commonurl 路径 (this.commonUrlObj.commonUrl) 而不是 (http://localhost:3000) 那么如何使用 angular 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'){};
}

【问题讨论】:

    标签: html css angular angular6


    【解决方案1】:
    getUrl(){
      return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
    }
    

    【讨论】:

    • 什么给了“getUrl()”?
    【解决方案2】:

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

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

    【讨论】:

    • 这部分 ${this.commonUrlObj.commonUrl} 不会渲染,它会显示为使用 ` 而不是整个字符串
    • 我使用 ` 表示整个字符串,但它给出了这种类型的错误 GET (localhost:4200/%60$%7Bthis.commonUrlObj.commonUrl%7D/… 404 (Not Found))
    • 哦,是的,我错过了 `` 引号 -> 编辑仍然不起作用?
    【解决方案3】:

    图片不能有背景图片。你可以做的是包装一个div 并给它一个背景:

    getUrl(){
      return "url('"+this.commonUrlObj.commonUrl+"'/placeholder.jpg')";
    }
    
    <div  [ngStyle]="{'background-image': getUrl()}>
      <img [src]="url" style="height: 400px;width: 400px">
    </div>
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-03
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 2010-10-06
        • 2018-01-08
        相关资源
        最近更新 更多