import { ChangeDetectorRef, Directive, HostBinding, Input, OnChanges, OnDestroy, } from '@angular/core'; import { Subscription, } from 'rxjs'; import { ImagePreloaderService, } from './../../services/index'; @Directive({ selector: '[background-image-fade-in]', }) export class BackgroundImageFadeInDirective implements OnChanges, OnDestroy { @Input('background-image-fade-in') public backgroundImageUrl: string; @HostBinding('style.backgroundImage') public hostBackgroundUrl: string; @HostBinding('class.u-background-image-fade-in--loaded') public isLoaded = false; private _subscription: Subscription; constructor( private _imagePreloaderService: ImagePreloaderService, private _changeDetectorRef: ChangeDetectorRef, ) {} public ngOnChanges() { this.isLoaded = false; this._subscription = this._imagePreloaderService.load(this.backgroundImageUrl) .subscribe(() => { this.hostBackgroundUrl = `url(${this.backgroundImageUrl})`; this.isLoaded = true; this._changeDetectorRef.markForCheck(); }); } public ngOnDestroy() { this._subscription.unsubscribe(); } }