showIfLoggedIn.directive.ts
import { Directive, Input } from '@angular/core';
import { TemplateRef, ViewContainerRef } from '@angular/core';
import { select } from "ng2-redux";
import { Observable } from "rxjs";
@Directive({selector: '[showIfLoggedIn]'})
export class ShowIfLoggedInDirective {
subscription;
@Input('showIfLoggedIn') renderTemplate;
@select(["session", "isLoggedIn"]) isLoggedIn$ : Observable<boolean>
constructor( private templateRef : TemplateRef<any>,
private viewContainer : ViewContainerRef ) {
}
ngOnInit() {
this.subscription = this.isLoggedIn$.subscribe(isLoggedIn => {
if( isLoggedIn ) {
if( this.renderTemplate ) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
} else {
if( this.renderTemplate ) {
this.viewContainer.clear();
} else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
});
}
}
ngOnDestory() {
this.subscription.unsubscribe();
}
}