Skip to content

Instantly share code, notes, and snippets.

@Dviejopomata
Last active July 2, 2018 22:35
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 Dviejopomata/693888d65efe5ef7d6e4f7612835e0fd to your computer and use it in GitHub Desktop.
Save Dviejopomata/693888d65efe5ef7d6e4f7612835e0fd to your computer and use it in GitHub Desktop.
Directive like *ngIf
<h1 *appAuthorization="{resource:'app',operation:'read'}">You now have access to read the resource app</h1>
import {
Directive,
EmbeddedViewRef,
Input,
TemplateRef,
ViewContainerRef,
} from "@angular/core"
class AuthorizationContext {
public resource: any = null
public operation: any = null
}
@Directive({
selector: "[appAuthorization]",
})
export class AuthorizationDirective {
@Input()
set appAuthorization({ resource, operation }: any) {
this._context.resource = resource
this._context.operation = operation
this.updateView()
}
private _context: AuthorizationContext = new AuthorizationContext()
private _thenTemplateRef: TemplateRef<AuthorizationContext> | null = null
private _thenViewRef: EmbeddedViewRef<AuthorizationContext> | null = null
constructor(
private _viewContainer: ViewContainerRef,
templateRef: TemplateRef<AuthorizationContext>,
) {
this._thenTemplateRef = templateRef
}
private updateView() {
const isAuthorized = this.isAuthorized()
if (isAuthorized) {
this._viewContainer.clear()
if (this._thenTemplateRef) {
this._thenViewRef = this._viewContainer.createEmbeddedView(
this._thenTemplateRef,
this._context,
)
}
}
}
private isAuthorized() {
return (
this._context.resource === "crud" && this._context.operation === "read"
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment