Igor Simic
1 year ago

Angular routing - how to load different component for same route


How to load different component under same route in Angular. For example, if user lands on home page and he is not logged in, we want to show him landing page, but if he is logged in for same url we want to show him logged in section page, for example lates news page. This can be done in Angular routing module.
How? Here is the answer.

So, let's say we have a route in Angular routing module for home page which is loading component HomePage:
{
  path: '', 
  component: HomePageComponent,
},
and we want to dynamically load component based on user status. If he is not logged in we will show home page, but if he is logged in we want to show Dashboard page (component). 
In Order to achieve this we will use AuthGuard where we will check is the user authenticated or not. So let's create AuthGuard
In your terminal execute this command:
ng g g Guards/Auth
ng g g  means -> ng generate guard and it will generate AuthGard in Guards folder.

In our auth guard we will include AuthService where we already have method to check is user authenticate or not. 

AuthGuard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {AuthService} from '../Services/auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor (
      public auth: AuthService

  ){}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

      const isLoggedIn = this.auth.isAuthenticated();

      return isLoggedIn.pipe(map((loggedInValue) => {

        if(loggedInValue){

          return true;

        }else{
            

          return false;

        }

      }));


  }

}
As you can see, here we are just returning true or false based on user logged in status.
Now we can use this in our Angular router.

First we will create new function in Angular router where we will decide which Component we will load based on user status:
export function getHomeComponent(): Type<Component> {

  if(AuthGuard.prototype.canActivate){

    return <Type<Component>>DashboardComponent;

  }else{

    return <Type<Component>>HomePageComponent;

  }


}

So, now instead of "hardcoding" the component name for home route we can use this function:
{
  path: '', 
  component:getHomeComponent(),
},

This technic can be used in some other scenarios, for example if you want to A/B test some landing pages. You will have a route for landing page and then you can create a Guard which will contain logic for deciding which page (component) needs to be served based on your A/B test settings.

But be careful, do not use this on pages  which you want to index in search engines, because serving different content under same URL is not allowed by Google and other search engines. 

In our example this is fine, search engines will always see "not logged" in page and regular users can login in and see different page (component) under home page URL.