user26776 user26776 - 3 months ago 30
TypeScript Question

How to Hide and Show Menu in Angular 2

I can hide some of the menu when the token is empty, but I am not being able to do it without refreshing the page.

That is the code I already have:

@Component({
selector: 'my-app',
template: `<h1>{{title}}</h1>
<div><h2>{{resultcooki}}</h2></div>
<nav>
<div *ngIf="token!=''">
<a [routerLink]="['/all']" routerLinkActive="active" >All</a>
<a [routerLink]="['/one']" >ONE</a>
<a [routerLink]="['/post']" >Post</a>
</div>
<a [routerLink]="['/login']" >Login</a>
</nav>
<router-outlet></router-outlet>`,
directives:[ROUTER_DIRECTIVES],
providers: [SymfonyService]

})

export class AppComponent {
title = 'Test';
token:string = this.getCookie("Cookie");

private getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let caLen: number = ca.length;
let cookieName = name + "=";
let c: string
for (let i: number = 0; i < caLen; i += 1) {
c = ca[i].replace(/^\s\+/g, "");
if (c.indexOf(cookieName) == 0) {
return c.substring(cookieName.length, c.length);
}
}
return "";
}

}


Any help?

Answer

That is because the token initialize it's value when the page load, that's the reason why you need to refresh the page.

I suggest you, to add a function to check the this.getCookie("Cookie"); value instead of checking the token variable value directly.

Try something like:

@Component({
    selector: 'my-app',
    template: `<h1>{{title}}</h1>
    <div><h2>{{resultcooki}}</h2></div>
    <nav>
    <div *ngIf="showMenu()"> 
    <a [routerLink]="['/all']" routerLinkActive="active" >All</a>
    <a [routerLink]="['/one']" >ONE</a>
    <a [routerLink]="['/post']" >Post</a>
    </div>
    <a [routerLink]="['/login']" >Login</a>
    </nav>
    <router-outlet></router-outlet>`,
    directives:[ROUTER_DIRECTIVES],
    providers: [SymfonyService]

})

export class AppComponent {
title = 'Test';

private getCookie(name: string) {
    let ca: Array<string> = document.cookie.split(';');
    let caLen: number = ca.length;
    let cookieName = name + "=";
    let c: string
    for (let i: number = 0; i < caLen; i += 1) {
        c = ca[i].replace(/^\s\+/g, "");
        if (c.indexOf(cookieName) == 0) {
            return c.substring(cookieName.length, c.length);
        }
    }
    return "";
}
showMenu(){
    return (this.getCookie("Cookie") != '');
}
}