Skip to content

Instantly share code, notes, and snippets.

@nivrith
Forked from fer-ri/background-image.ts
Created July 6, 2018 06:14
Show Gist options
  • Save nivrith/1ac1a6c382b7b9f9f53dd4e05d79e7cc to your computer and use it in GitHub Desktop.
Save nivrith/1ac1a6c382b7b9f9f53dd4e05d79e7cc 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment