4

When using @HostBinding to bind a property to the background-image of my component, it doesn't work when I specify an image URL.

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

When inspecting the DOM, we can find <demo>something</demo> -> NOT GOOD


Second example :

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

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

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

This time, when inspecting the DOM, we can find <demo style="background-image: none;">something</demo> -> GOOD


I tried with background instead of background-image, it works with a color like "blue" but still doesn't work with an URL.

I also tried to dynamically change the value later with a setTimeout inside ngAfterViewInit(), it works when changing from "none" to "blue", but not with an URL, the value stay "none".

Noémi Salaün
  • 4,866
  • 2
  • 33
  • 37
  • Have you tried setting the url in quotes like so: `backgroundImage = 'url("http://placekitten.com/g/200/300")';` – Maximilian Riegler May 18 '16 at 12:41
  • 1
    Yes, I tried with quotes. I tried with a function insted of a variable. I tried with the `host` property inside the `@Component` decorator. Always the same result. – Noémi Salaün May 18 '16 at 12:43

1 Answers1

5

It's a behavior because the style sanitizer of Angular2 was very restrictive... It seems to have been recently fixed.

See this issue:

Egel
  • 1,796
  • 2
  • 24
  • 35
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360