By: Netanel Basal (Angular Expert) and Yaron Biton, misterBIT.co.il CTO

Aspect Oriented Programming in Angular 2

When dealing with cross cutting concerns, AOP (Aspect Oriented Programming) is your best friend. In Angular 2, this is achievable by writing your own Directive.

Background and scope

I’m working on my Angular 2 project with ng2redux which is based on the Redux library.

After implementing the SignIn/Signout logic with all the Redux good stuff like actions, reducers, and one-way direction flow, I came to the part that I needed to show or hide templates based on the user session status.

The Naïve[rbose] approach

My first approach was in every component to subscribe to the session observable from my store and render what I need based on the status.

So for example in my navigation component:

And then continue following this approach in all my components that needed this kind of functionality.

It Feels Smelly.

Not DRY; a cross cutting concern is handled in every component. Creates many observables.

The solution:

Directive for managing component behavior triggered by login/logout events.

When dealing with cross cutting concerns, AOP (Aspect Oriented Programming) is your best friend. In Angular 2, this is achievable by writing your own Directive. In this case, we are talking about a Structural Directive (such as *ngIf):

“ A Structural directive changes the DOM layout by adding and removing DOM elements. ”

Let me show you the final code and then we can go over the details:

ShowIfLoggedInDirective Explained

We need access to the template ( TemplateRef ) and something that can render its contents ( ViewContainerRef ), so we inject both into our component.

Note: If you are asking yourself from where this templateRef coming from, the asterisk in the directive is only syntactic sugar for this code for example:

So the templateRef is just the template tag. Piece-of-mind has been successfully restored.

There is this bit where we subscribe to the isLoggedIn value from the ng2redux store, (run this function whenever the isLoggedIn status change) this is something that is not for this article to cover. Do check out how RxJS and Redux are best buddies to create flux based architectures in Angular.

Victorious!

Now we can use this directive everywhere we want, this auth-aware aspect is handled in a good DRY way:

Cheers!

☞ Please tap or click “︎❤” to help to promote this piece to others.