【问题标题】:background-image isn't working in Angular6 using ngStyle背景图像在使用 ngStyle 的 Angular6 中不起作用
【发布时间】:2019-10-03 08:21:39
【问题描述】:

我想使用 ngStyle 动态设置背景图像。但它没有加载任何东西。这是我的 HTML

<div
  id="banner-cover"
  class="bg-parallax animated fadeIn"
  [ngStyle]="{
    'background-image': backgroundImage
  }"
>
...
</div>

这是我在 ts 中定义的 backgroundImage() 方法。这里我使用了推荐here的Domsanitizer。

export class BannerComponent implements OnInit {
  public _backgroundImage = "'url('../../../../assets/images/bg-banner.jpg')'";
  constructor(private sanitizer:DomSanitizer) { }

  ngOnInit() {
  }
  get backgroundImage() {
    return this.sanitizer.bypassSecurityTrustStyle( this._backgroundImage );
  }
}

【问题讨论】:

    标签: angular6 ng-style


    【解决方案1】:

    需要调用getBackgroundImage()方法:

    [ngStyle]="{ 'background-image': getBackgroundImage() }"

    【讨论】:

    • 我尝试过调用方法和属性。他们都没有工作。这里我展示了属性调用。
    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 2015-09-17
    • 2023-03-03
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    相关资源
    最近更新 更多