Last active
January 17, 2022 10:15
-
-
Save mseemann/4b3c74bd1372a89ecbd06e29fb3bea12 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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