如何使用@HostBinding将背景图像添加到Angular 2+指令中?

jky*_*sey 0 background-image angular2-directives angular2-hostbinding angular

我需要创建一个Angular 2+(我在4.x)指令(非组件),通过添加背景图像@HostBinding.我知道我很亲密,但是当我检查它时,我会看到background-image: noneChrome的检查员.

import { Directive, HostBinding } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Directive({
    selector: '[myDirectiveWithBackgroundImage]'
})
export class MyDirective {

    @HostBinding('style.background-image')
    public backgroundImage: SafeStyle;

    constructor(private sanitizer: DomSanitizer) {
        this.backgroundImage = this.sanitizer.bypassSecurityTrustStyle(
            'url(assets/images/favicon16.png) no-repeat scroll 7px 7px;'
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我的资产/ images/favicon.16png由webpack提供.我已经试过各种路径选项,/assets,~/assets,等...但background-image总是none

https://plnkr.co/edit/5w87jGVC7iZ7711x7qWV?p=preview

Ale*_*sky 6

背景图像不会接受简写属性像background-repeat不重复background-size7px的7px的.要使用背景速记属性,你需要使用CSS background@HostBinding('style.background'),而不是@HostBinding('style.background-image')像这样:

@HostBinding('style.background')
public background: SafeStyle;

constructor(private sanitizer: DomSanitizer) {
  this.background = this.sanitizer.bypassSecurityTrustStyle(
    'url("//ssl.gstatic.com/gb/images/i1_1967ca6a.png") no-repeat scroll 7px 7px'
  );
}
Run Code Online (Sandbox Code Playgroud)

看到这个分叉的plunker演示了实际的功能.

希望这有帮助!