Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Last active January 17, 2017 16:05
Show Gist options
  • Save NetanelBasal/763e02c4fff7e645afb7a64b327cbbbf to your computer and use it in GitHub Desktop.
Save NetanelBasal/763e02c4fff7e645afb7a64b327cbbbf to your computer and use it in GitHub Desktop.
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment