Last active
May 21, 2021 15:20
-
-
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
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 {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