import {AfterViewInit, Directive, Input, OnDestroy, TemplateRef, ViewContainerRef} from '@angular/core'; import {Subscription} from 'rxjs'; import {PackageService} from '../../services/package.service'; import * as appCommonReducer from '../../reducers/app-common.reducer'; import {Store} from '@ngrx/store'; @Directive({ selector: '[fmHasPackage]', }) export class HasPackageDirective implements OnDestroy, AfterViewInit { @Input() set fmHasPackage(packageIdentifier: string) { this.packageIdentifier = packageIdentifier; this.updateView(); } @Input() set fmHasPackageThen(thenTemplate: TemplateRef) { this.thenTemplate = thenTemplate; this.updateView(); } @Input() set fmHasPackageElse(thenTemplate: TemplateRef) { this.elseTemplate = thenTemplate; this.updateView(); } private packageIdentifier: string; private thenTemplate: TemplateRef; private elseTemplate: TemplateRef; private packSub: Subscription; constructor(private hostTemplateRef: TemplateRef, private viewContainerRef: ViewContainerRef, private store: Store, private packageService: PackageService) { this.thenTemplate = hostTemplateRef; this.packSub = this.store.select(appCommonReducer.SelectGetValidUserPackages).subscribe((_) => { this.updateView(); }); } ngAfterViewInit() { this.updateView(); } updateView() { this.viewContainerRef.clear(); if (this.packageService.hasPackage(this.packageIdentifier)) { this.viewContainerRef.createEmbeddedView(this.thenTemplate); } else if (this.elseTemplate) { this.viewContainerRef.createEmbeddedView(this.elseTemplate); } } ngOnDestroy() { if (this.packSub) { this.packSub.unsubscribe(); } } }