Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good template strategy for authentication in Angular 2

I currently have an Angular 2 app up and running that looks as follows:

App.component is bootstrapped when visiting the site. The template for App.component has all component tags (for example menu.component, search.component and the router-outlet).

What I basically need is the following: currently a visitor is directly redirected to the Login page because the user needs to login. He is still able to see the menu and all components that are only there for logged in users. What would be the best strategy to add an extra template layer, so not logged in users get redirected?

like image 462
hY8vVpf3tyR57Xib Avatar asked May 08 '16 13:05

hY8vVpf3tyR57Xib


1 Answers

The way that I've done it is to use the *ngIf directive to "hide" those elements until the user is authenticated. I use quotes around the word hide above because angular doesn't actually hide that part of the template, it actually doesn't render it at all so it's not in the DOM.

That means that unless the user logs in, only your login screen will be rendered.

More details on *ngIf can be found here:

https://angular.io/docs/ts/latest/guide/structural-directives.html#!#ngIf

ex.

@Component({
    selector: 'your-selector',
    template: `
        <div *ngIf='isLoggedIn() === true'>
            <menu-component></menu-component>
            <search-component></search-component>
            <router-outlet></router-outlet>
        </div>
        <div *ngIf='isLoggedIn() !== true'>
            <login-component></login-component>
        </div>
    `
    ...
})
export class YourSelectorComponent {
    isLoggedIn() {
        //check if logged in
    }
}
like image 122
Gab Avatar answered Sep 21 '22 03:09

Gab