Created
June 15, 2023 07:02
-
-
Save space11/db7b570b50b1aeb3bd031810a38c30c9 to your computer and use it in GitHub Desktop.
Angular Structural Directive - Hide element base on condition
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 { | |
| 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