💉 Shot #8: How to create a structural directive *isAuthorized (custom *ngIf)

Dmitry Nehaychik
May 14, 2019 · 2 min read
Image for post
Image for post

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:

Useful Links

Angular Shots

Community-driven Angular how-to collection.

Thanks to Nikita Poltoratsky

Dmitry Nehaychik

Written by

Nebular team at @akveo_inc. Products engineering addict.

Angular Shots

Community-driven Angular how-to collection. For contribution or collaboration tweet or DM!

Dmitry Nehaychik

Written by

Nebular team at @akveo_inc. Products engineering addict.

Angular Shots

Community-driven Angular how-to collection. For contribution or collaboration tweet or DM!

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface.

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox.

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store