๐ Shot #8: How to create a structural directive *isAuthorized (custom *ngIf)
Introduction
Angular has quite a powerful template syntax. Moreover, we are able to extend it creating custom structural directives. This gives us the ability to re-use repeated code parts making code cleaner and simpler.
Letโs assume that we need to show/hide elements based on the user authentication status. For instance, we have a method that checks if the user has logged in:
Now we can use the isAuthorized
variable to check this status in the template:
In case we have these checks in multiple templates, our app will have duplicated code blocks across the app, making it harder to maintain.
Luckily, we can move these code parts into a separated structural directive and use it directly in the template:
Step 1: Create a structural directive
Create a directive class and give it a proper selector:
Step 2: Inject TemplateRef and ViewContainerRef
All magic appears behind the *
sign. When Angular meets a directive that starts with *
it wraps the whole host element into invisible <ng-template></ng-template>
element, allowing us to inject the host element into the directive and manipulate it respectively (show or hide, for instance):
Step 3: Create/remove the template
Now, based on the data returned from userService
, we can either remove the template from the output or create it there:
Step 4: Register the directive
Shot
And here is the final shot ready for injection: