Angular 6 - Renderer2 - not able to show image background

Viewed 2451

trying to create custom directive for learning purpose. Am not able to identify the issue why the renderer2 in Angular 6 is not showing image background.

i've using cli, so there is no issue in registering directive in app.module.ts

@Directive({
  selector: '[bgIMG]'
})
export class MyCustomStyleDirective {
 // private url = "http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg" 

  constructor(elm : ElementRef, renderer2:Renderer2) {
    renderer2.setStyle(elm.nativeElement, 'background-image', 'url ("http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg")')    
   }
}

html

<div bgIMG></div>

where am wrong.? i don't find any console errors also.

update

import { Directive,ElementRef, Renderer2, HostListener } from '@angular/core';

@Directive({
  selector: '[bgIMG]'
})
export class MyCustomStyleDirective {

  constructor( renderer: Renderer2,  el: ElementRef) {

    renderer.setStyle(el.nativeElement, 'background-image','http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg');
    renderer.setStyle(el.nativeElement, 'font-weight','bold');

   }

}


html
-----

<div class="container">
  <div class="row">
    <div bgIMG>
      <p>some text</p>
    </div>
  </div>
</div>

Thanks in advance

2 Answers

you are doing correct but one correction is please remove space between ==> "url ()" ,

please look below code. it will work for you.

import { Directive, ElementRef, Renderer2 } from "@angular/core";

@Directive({
    selector: '[bgIMG]'
  })
  export class MyCustomStyleDirective {
    constructor(elm : ElementRef, renderer2:Renderer2) {
      renderer2.setStyle(elm.nativeElement, 'background-image', 'url(http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg)')    
     }
  }

You have to use background-image, which is the correct css style property:

renderer2.setStyle(
  elm.nativeElement, 
  'background-image', 
  'url("http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg")'
) 

But to be able to use an url, you have to cast it to a safe style first:

constructor(elm : ElementRef, renderer2:Renderer2, san: DomSanitizer) {
  const bg = san.bypassSecurityTrustStyle('url("http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg")')

  renderer2.setStyle(
    elm.nativeElement, 
    'background-image', 
    bg
  ) 
}

On the other hand, you can also just use the HostBinding property:

@Directive({
  selector: '[bgIMG]'
})
export class MyCustomStyleDirective {
  @HostBinding('style.background-image')
  get bg(): SafeStyle {
    return this.san.bypassSecurityTrustStyle(`url("${this.url}")`);
  } 

  private url = "http://www.publicdomainpictures.net/pictures/50000/velka/flower-meadow.jpg" 

  constructor(readonly san: DomSanitizer) {}
}
Related