authenticationangular-ng-ifrouter-outletangular12

How to make ngIf condition for user login - app-container router-outlet


I am repeatedly running in an issue which I believe has everything to do with my ngIf conditions in my app.component.html. Here is my code:

<!-- nav -->
<div class="wrapper" *ngIf="user">
     <div class="sidebar" >
        <sidebar-cmp></sidebar-cmp>
    </div> 
     <div class="main-panel">
        <navbar-cmp></navbar-cmp>
        <div class="content">
            <router-outlet></router-outlet>
        </div>
    </div>
</div> 



<!-- main app container -->
<div class="app-container" [ngClass]="{ 'bg-light': user }" *ngIf="!user">
    <alert></alert>
    <router-outlet></router-outlet>
</div>

There are two ngIf conditions here.

If I have only the first one then when I log out I cannot redirect to my login screen. What happens is the Navbar and sidebar disappear but the page itself remains although the URL says it's at login. The router-outlet doesn't go away.

If I have only the second one then my sidebar links don't work and the router-outlet is basically blank.

If I have both conditions then once logged in and using the sidebar, the URL changes but the page doesn't load.

If I have neither condition then Navbar and sidebar appear on login screen when they ought not.

Help!

I'm not very proficient in Angular just yet so I was hoping for some direction here.

My latest thought is to have an *ngIf user; else something. I'm not sure. How could I resolve this?


Solution

  • I solved it! This question is exactly what I was thinking but couldn't get it to work but now it works!!

    How to use *ngIf else?

    This is the solution:

    <div class="wrapper" *ngIf="user; else loggedOut">
        <div class="sidebar">
            <sidebar-cmp></sidebar-cmp>
        </div>
        <div class="main-panel">
            <navbar-cmp></navbar-cmp>
            <div class="content">
                <router-outlet></router-outlet>
            </div>
        </div>
    </div>
    
    
    <ng-template #loggedOut>
        <div class="app-container" [ngClass]="{ 'bg-light': user }">
            <alert></alert>
            <router-outlet></router-outlet>
        </div>
    </ng-template>
    

    Whoop whoop!