Skip to content

Instantly share code, notes, and snippets.

@fer-ri
Created May 24, 2016 06:33
Show Gist options
  • Select an option

  • Save fer-ri/314cd43a32a417f176d39a6084af5829 to your computer and use it in GitHub Desktop.

Select an option

Save fer-ri/314cd43a32a417f176d39a6084af5829 to your computer and use it in GitHub Desktop.
Background Image Style Directive for Angular 2 and Ionic 2
import {Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[background-image]'
})
export class BackgroundImage {
private el: HTMLElement;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
@Input('background-image') backgroundImage: string;
ngAfterViewInit() {
this.el.style.backgroundImage = 'url(' + this.backgroundImage + ')';
}
}
<div class="header" background-image="{{ item.featured_image }}">
<!--some content-->
</div>
<!-- alternative -->
<div class="header" [ngStyle]="{'background-image': 'url(' + item.featured_image + ')'}">
<!--some content-->
</div>
@mtrl

mtrl commented Dec 7, 2016

Copy link
Copy Markdown

:) Very useful! Thanks.

@ubarsaiyan

Copy link
Copy Markdown

Thanks :)

@aehven

aehven commented Aug 29, 2017

Copy link
Copy Markdown

Very nice. Thanks very much for publishing this.

@souuu

souuu commented Oct 20, 2017

Copy link
Copy Markdown

Awesome !

@mstar95

mstar95 commented Mar 9, 2018

Copy link
Copy Markdown

Awesome!

@salazarr-js

Copy link
Copy Markdown

super util ❤️

@salazarr-js

salazarr-js commented Mar 21, 2018

Copy link
Copy Markdown

Después de haber usado esta directiva por un tiempo, me di cuenta de que hay un problema cuando la imagen que le paso al Input es asíncrona, así que lo solucioné agregando ngOnChages para manejar los futuros cambios en el Input. También use el Renderer2 como recomendación de este post.

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

@Directive({
  selector: '[background-image]'
})
export class BackgroundImageDirective {
  private el: HTMLElement;
  @Input('background-image') backgroundImage: string;

  constructor(private renderer: Renderer2, private elRef: ElementRef) {
    this.el = this.elRef.nativeElement;    
  }

  ngAfterViewInit() {
    this.setBackgroundImage();
  }
  
  ngOnChanges(changes: SimpleChanges) {
    if ( changes['backgroundImage'] ) 
      this.setBackgroundImage();
  }
  
  setBackgroundImage(){
    this.renderer.setStyle(this.el, "backgroundImage", `url(${ this.backgroundImage })`);
  }
}

Espero sea de utilidad 😄

@SadykZ

SadykZ commented May 1, 2018

Copy link
Copy Markdown

Thanks, very useful!

@gbrits

gbrits commented May 22, 2018

Copy link
Copy Markdown

For those on Ionic3 that used ionic generate directive backgroundImage to add this code, don't forget to:

import { DirectivesModule } from '../directives/directives.module';

and then add it into the app.module.ts imports, eg:

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    DirectivesModule
  ], (...)

@AlonsoK28

Copy link
Copy Markdown

angular 8

I do this on

app.ts

this.backgroudImage = { "background-image": url('${data.background_image}') };

and this in

app.html

<section class="jumbotron" [ngStyle]="backgroudImage"> <div class="container"> <div class="row text-center"> <h2>{{Game?.name}}</h2> </div> </div> </section>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment