Skip to content

Instantly share code, notes, and snippets.

@space11
Created June 15, 2023 07:02
Show Gist options
  • Save space11/db7b570b50b1aeb3bd031810a38c30c9 to your computer and use it in GitHub Desktop.
Save space11/db7b570b50b1aeb3bd031810a38c30c9 to your computer and use it in GitHub Desktop.
Angular Structural Directive - Hide element base on condition
import {
Directive,
TemplateRef,
ViewContainerRef,
OnInit,
} from "@angular/core";
import { AuthService } from "./auth.service";
@Directive({
selector: "[isAuthenticated]",
})
export class IsAuthenticatedDirective implements OnInit {
constructor(
private viewContainer: ViewContainerRef,
private tpl: TemplateRef<any>,
private auth: AuthService
) {}
ngOnInit() {
this._createView();
}
private _createView() {
if (this.auth.isAuthenticated()) {
this.viewContainer.createEmbeddedView(this.tpl);
} else {
this.viewContainer.clear();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment