nacho10f
nacho10f

Reputation: 5886

Angular routing multiple components under home page path

Let's say I want to have a similar setup as facebook.com. When logged out, the content of this url is a regular home page with info about facebook and a login form. When logged in, this same url (facebook.com, no specific route) is now displaying a feed of data.

What is the proper way of implementing this?

I thought about simply having something like:

<div *ngIf="isLoggedIn; else loggedOut">
  <internal-dashboard-component></internal-dashboard-component>
</div>

<ng-template #loggedOut>
  <external-home-component></external-home-component>
</ng-template>

But that seems a bit complex.

Is this a logical approach? Is there something that could be done with Angular routing that I am missing??

Upvotes: 4

Views: 2394

Answers (2)

Gustavo Morais
Gustavo Morais

Reputation: 588

Angular has something called URL Matcher. It's used for the case you've specified, two components under the same path. You can read more about it here.

It's use looks something like this:

{
 path: 'Path',
 matcher: firstMatcher,
 loadChildren: '../login/login.module'
},
{
 path: 'Path',
 matcher: secondMatcher,
 loadChildren: '../dashboard/dashboard.module'
}

You can read more about how to implement it in this comment to a similar question(how to put two components under the same path).

Also, your solution is feasible as well. I would add a little tweak to make it easier to implement though.

<div *ngIf="!isLoggedIn">
  <internal-dashboard-component></internal-dashboard-component>
</div>

<router-outlet *ngIf="isLoggedIn"></router-outlet>

By doing that you can use normally your routing as a regular angular application when the user is logged in.

Upvotes: 3

sixtyfive
sixtyfive

Reputation: 71

You could also check if the user is logged in or not when the app first starts and then route the user programmatically using instead of the *ngIf :

this.router.navigate(['/home']);

Keep in mind though that no matter what you do here in Angular is still all being handled on the client side so depending on what you are trying to secure you may want to look into handling this user check on the back end of your application.

Upvotes: 0

Related Questions