Skip to content

Instantly share code, notes, and snippets.

@mseemann
Last active January 17, 2022 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mseemann/4b3c74bd1372a89ecbd06e29fb3bea12 to your computer and use it in GitHub Desktop.
Save mseemann/4b3c74bd1372a89ecbd06e29fb3bea12 to your computer and use it in GitHub Desktop.
import {
Directive,
Input,
OnDestroy,
OnInit,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
import { Store } from '@ngrx/store';
import { User } from './user';
import { Subject, takeUntil } from 'rxjs';
import { Privilege } from './privilege';
@Directive({
selector: '[appHasPrivilegesWithStore]',
})
export class HasPrivilegesWithStoreDirective implements OnInit, OnDestroy {
private onDestroy$ = new Subject<void>();
constructor(
private vcRef: ViewContainerRef,
private tmpRef: TemplateRef<unknown>,
private store: Store<{ user: User }>
) {}
@Input()
appHasPrivilegesWithStore: Privilege[] | undefined = [];
@Input()
appHasPrivilegesWithStoreOrIsAdmin = false;
ngOnInit() {
this.store
.select('user')
.pipe(takeUntil(this.onDestroy$))
.subscribe((user) => {
this.vcRef.clear();
if (
user.hasOneOfPrivileges(this.appHasPrivilegesWithStore ?? []) ||
(this.appHasPrivilegesWithStoreOrIsAdmin && user.isAdmin())
) {
this.vcRef.createEmbeddedView(this.tmpRef);
}
});
}
ngOnDestroy() {
this.onDestroy$.next();
this.onDestroy$.complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment