Skip to content

Instantly share code, notes, and snippets.

@fdonzello
Last active May 21, 2021 15:20
Show Gist options
  • Save fdonzello/c4b687681b48bafa90c5c3147bf63a38 to your computer and use it in GitHub Desktop.
Save fdonzello/c4b687681b48bafa90c5c3147bf63a38 to your computer and use it in GitHub Desktop.
A simple component to wrap other components that can be shown only if the user is granted access to
import {Component, Input, OnInit} from '@angular/core';
import {UserTypes} from '../../models/models';
import {UserService} from '../../api/user.service';
import {map} from 'rxjs/operators';
@Component({
selector: 'app-if-granted',
template: `
<ng-container *ngIf="isGranted() | async">
<ng-content></ng-content>
</ng-container>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class IfGrantedComponent implements OnInit {
@Input() allowedRoles: UserTypes[];
constructor(private _user: UserService) {
}
ngOnInit(): void {
}
isGranted() {
return this._user.getUser().pipe(
map(u => hasType(u, ...this.allowedRoles))
);
}
}
export function hasType(u: User, ...values: UserTypes[]) {
for (const userType of values) {
if (u.type.name.toLowerCase() === userType.toLowerCase()) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment