has-any-authority.directive.ts 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
  2. import { Principal } from 'app/core/auth/principal.service';
  3. /**
  4. * @whatItDoes Conditionally includes an HTML element if current user has any
  5. * of the authorities passed as the `expression`.
  6. *
  7. * @howToUse
  8. * ```
  9. * <some-element *jhiHasAnyAuthority="'ROLE_ADMIN'">...</some-element>
  10. *
  11. * <some-element *jhiHasAnyAuthority="['ROLE_ADMIN', 'ROLE_USER']">...</some-element>
  12. * ```
  13. */
  14. @Directive({
  15. selector: '[jhiHasAnyAuthority]'
  16. })
  17. export class HasAnyAuthorityDirective {
  18. private authorities: string[];
  19. constructor(private principal: Principal, private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}
  20. @Input()
  21. set jhiHasAnyAuthority(value: string | string[]) {
  22. this.authorities = typeof value === 'string' ? [value] : value;
  23. this.updateView();
  24. // Get notified each time authentication state changes.
  25. this.principal.getAuthenticationState().subscribe(identity => this.updateView());
  26. }
  27. private updateView(): void {
  28. this.principal.hasAnyAuthority(this.authorities).then(result => {
  29. this.viewContainerRef.clear();
  30. if (result) {
  31. this.viewContainerRef.createEmbeddedView(this.templateRef);
  32. }
  33. });
  34. }
  35. }