This is not so difficult. All you need is a parent component which is usually the AppComponent. Inside of the AppComponent you have your main router-outlet.
And this router-outlet loads either the LoginComponent or the Component that is only for the users available who are logged in.
This could be your router configuration of your root AppComponent:
{
path: 'login',
component: LoginComponent,
canActivate: [AuthenticationGuard]
},
{
path: 'app',
canActivate: [AuthenticationGuard],
component: HomeComponent,
children: [
...
]
}
Inside your router configuration you can use CanActivate. CanActivate is a guard that checks if the user has the permission to navigate to a route/component of your application.
In the example above the AuthenticationGuard checks if the user is logged in or not. So now you can protect your application with this guard. If the guard gets the information that you are logged in it can navigate you automatically to the HomeComponent.
See this guard as an example to protect your HomeComponent from unauthorized users:
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private loginService: LoginService, private router: Router) { }
canActivate() {
if (this.loginService.isLoggedIn() !== true) {
this.router.navigate(['/login']);
return false;
} else {
return true;
}
}
}
If the guard returns true, that means that the router will navigate to the specified route. If it returns false, the router protect the route by redirecting the user to the login page.
So now your are switching between both components of the AppComponent's router-outlet. In the HomeComponent you should create another router-outlet if you want to have more then one component for your application. You define these components as the childcomponents of the HomeComponent.
To sum it up:
So you can see the HomeComponent as the root component of the part of your application that is protected.