0

我需要通過@HostBinding創建一個Angular 2+(我是4.x)指令(不是組件),它增加了一個背景圖像。我知道我很接近,但是當我檢查它時,我在Chrome的檢查器中看到background-image: none如何使用@HostBinding將背景圖像添加到Angular 2+指令?

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;' 
    ); 
    } 
} 

我的資產/ images/favicon.16png由webpack提供服務。我已經試過各種路徑選項,/assets~/assets,等等...但background-image總是none

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

+0

你可以創建一個plunker嗎? –

+0

其中是/資產相對於/ src? – Vega

+0

@Maximus https://plnkr.co/edit/5w87jGVC7iZ7711x7qWV?p=preview 但是,在plunkr中,它不會在所有**處添加'background-image ** **。它確實添加了其他樣式。 – jkyoutsey

回答

4

background-image接受簡寫的屬性,如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' 
); 
} 

看到這個分叉plunker揭示了動作的功能。

希望有幫助!

+0

15年以上的HTML開發,我應該知道!謝謝!值得注意的是我有一個流浪的'''在字符串的末尾也被打破了。我已將我的運動員更新爲工作狀態。 – jkyoutsey