【问题标题】:Angular2 @HostBinding cannot bind on background-image style [duplicate]Angular2 @HostBinding 无法绑定背景图像样式 [重复]
【发布时间】:2016-09-14 22:58:13
【问题描述】:

当使用@HostBinding 将属性绑定到我的组件的背景图像时,当我指定图像 URL 时它不起作用。

Angular2 RC-1 的第一个示例:

import {Component, HostBinding} from "@angular/core";

@Component({
    selector: 'demo',
    template: 'something'
})
export class DemoComponent {

    @HostBinding('style.background-image')
    backgroundImage = 'url(http://placekitten.com/g/200/300)';
}

在检查 DOM 时,我们可以发现 <demo>something</demo> -> NOT GOOD


第二个例子:

import {Component, HostBinding} from "@angular/core";

@Component({
    selector: 'demo',
    template: 'something'
})
export class DemoComponent {

    @HostBinding('style.background-image')
    backgroundImage = 'none';
}

这一次,在检查 DOM 时,我们可以找到<demo style="background-image: none;">something</demo> -> GOOD


我尝试使用background 而不是background-image,它适用于"blue" 之类的颜色,但仍不适用于URL。

我还尝试稍后在ngAfterViewInit() 中使用setTimeout 动态更改值,当从"none" 更改为"blue" 时它可以工作,但不能使用URL,值保持"none"。

【问题讨论】:

  • 您是否尝试过将网址设置在引号中,如下所示:backgroundImage = 'url("http://placekitten.com/g/200/300")';
  • 是的,我尝试使用引号。我尝试使用包含变量的函数。我尝试在 @Component 装饰器中使用 host 属性。总是一样的结果。

标签: typescript angular styles


【解决方案1】:

这是一种行为,因为 Angular2 的样式清理程序非常严格……最近似乎已修复。

看到这个问题:

【讨论】:

  • 它适用于DomSanitizationService.bypassSecurityTrustStyle()。感谢您的建议。
猜你喜欢
  • 2021-03-20
  • 2018-12-23
  • 1970-01-01
  • 2016-05-16
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
相关资源
最近更新 更多