1

I need to create an Angular 2+ (I'm in 4.x) Directive (NOT a Component) that adds a background image via @HostBinding. I know I'm close, but when I inspect it I see background-image: none in Chrome's inspector.

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

My assets/images/favicon.16png is being served by webpack. I've tried all sorts of path options, /assets, ~/assets, etc... But background-image is always none

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

jkyoutsey
  • 1,969
  • 2
  • 20
  • 31

3 Answers3

7

background-image does not accept shorthand properties like background-repeat's no-repeat and background-size's 7px 7px. To use background shorthand properties you would need to use CSS background for the @HostBinding('style.background') instead of @HostBinding('style.background-image') like:

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

See this forked plunker demonstrating the functionality in action.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • 15+ years of HTML dev and I should have known that! Thanks! Worth noting that I had a stray `;` at the end of the string that was breaking it too. I've updated my plunker to a working state. – jkyoutsey Jul 21 '17 at 18:34
  • If you want to include `background-cover` it needs to be in this format with a `/` : `url("assets/images/backgrounds/bathroom.png") left center / cover no-repeat` – Simon_Weaver Aug 01 '18 at 20:58
1

I managed to get Hostbinding working with the background-image property.

Just put style inside the Hostbinding like this @HostBinding('style') backgroundImage: safeStyle; instead of @HostBinding('style.background-image') backgroundImage: safeStyle;

@HostBinding('style') backgroundImage: safeStyle;

this.backgroundImage = this.sanitizer.bypassSecurityTrustStyle(`background-image: url('${url}')`);
WoutVC
  • 23
  • 4
0

@Alexander Thanks for including the sanitizer code.

Interestingly I'm only seeing this necessary if I have extra parameters after the URL. If I only have a URL it works, but once I add 'left top' then I get this error :

enter image description here

Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689