Angular Interview Questions : Routing & Route Guards
August 10, 2023
Q.1 : Which module is imported for routing?
Ans : The moduleRouterModule
is imported for routing.
import { RouterModule } from '@angular/router';
Q.2 : What is difference between Route
and Routes
?
Ans :
Route : A
Route
is a configuration object that defines single route.
{ path: 'manage-user', component: ManageUserComponent }
Routes
is the set of Route
.
const routes: Routes = [ { path: 'manage-user', component: ManageUserComponent }, { path: 'update-user/:id', component: UpdateUserComponent } ]
Q.3 : How can you redirect a URL to another URL?
Ans : We can redirect a URL usingRoute.redirectTo
property.
{ path: ‘’, redirectTo: ‘/dashboard’, pathMatch: 'full' }
Q.4 : How can you handle ‘404 Not Found’ ?
Ans : To handle ‘404 Not Found’, use path as ** in route and create a component to associate with this path.{ path: '**', component: NotFound404Component }
NotFound404Component
will be executed.
Q.5 : What is the role of RouterModule.forRoot()
method to define routes?
Write a sample code.
Ans : The forRoot()
method creates and configures a module with all the router providers and directives.
Find the sample code to define route.
const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'user-detail/:id', component: UserDetailComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [ RouterModule ] }) export class AppRoutingModule{ }
Q.6 : How will you create route path with parameters and access its values?
Ans : To create route path with parameters, use colon (:) as following.{ path: 'get-user/:id', component: UserComponent }
UserComponent
will be invoked.
The value for id will be 100. To fetch the value of id in UserComponent
, use ActivatedRoute
and Params
.
@Component({ —— }) export class UpdateBookComponent implements OnInit { user: User = new User(); constructor(private route: ActivatedRoute, private userService: UserService, private location: Location) { } ngOnInit(): void { this.route.params.pipe( switchMap((params: Params) => this. userService.getUser(+params['id'])) ).subscribe(user => this.user = user); } --------- }
Params : Contains the parameter value.
Q.7 : What is the role of Angular Location
service?
Ans : The Location
service is used to navigate back and forward. For example.
@Component({ —— }) export class UserDetailComponent { constructor(private location: Location) { } goBack(){ this.location.back(); } goForward(){ this.location.forward(); } }
Q.8 : How will you navigate from one component path to another component path programmatically?
Ans : We can navigate from one component to another component usingRouter.navigate()
method.
Suppose we have a path as below.
{ path: 'update-user/:id', component: UpdateUserComponent }
Router.navigate()
method.
@Component({ — }) export class UserDetailComponent { constructor(private router: Router) { } updateUser(id: number) { this.router.navigate([‘/update-user’, id]); } }
Q.9 : How will you use RouterLink
and RouterLinkActive
?
Ans :
RouterLink : Binds the route with clickable HTML element such as anchor tag.
RouterLinkActive : A directive that binds the CSS class with HTML element and becomes active only when that element is clicked.
They are used as following.
<a routerLink="/manage-user" routerLinkActive="active-link">Manage User</a>
Q.10 : What is <router-outlet>
?
Ans : The <router-outlet>
acts as a placeholder that is filled dynamically based on the current router state. It marks the location where the router displays the view. Use it as following.
<router-outlet></router-outlet>
Q.11 : How will you create children path?
Ans : To create children path, we useRoute.children
property.
const userRoutes: Routes = [ { path: ‘dashboard’, component: DashboardComponent, children: [ { path: 'add', component: AddUserComponent } ] } ]
AddUserComponent
.
Q.12 : What is empty child routes?
Ans : Empty child route will be invoked by default for parent route.const userRoutes: Routes = [ { path: ‘dashboard’, component: DashboardComponent, children: [ { path: '', component: UserDetailComponent } ] } ]
Q.13 : In how many ways is a module loaded?
Ans : A module is loaded in three ways : Eager loading, Lazy loading, Preloading. Main module of application always loaded eagerly and feature module can be loaded in any ways.Q.14 : What is eager loading of modules?
Ans : In eager loading, all the feature modules are loaded before the application start. Suppose we have a feature module asUserRoutingModule
. To load it eagerly, just import it using @NgModule
in main application module.
@NgModule({ imports: [ --------- UserRoutingModule ], })
imports
metadata. The advantage of eager loading is that the subsequent request to the application will be faster. Eager loading is suitable for small size application.
Q.15 : What is lazy loading of modules?
Ans : In lazy loading all the feature modules are loaded on-demand. They are not loaded at application start, they are loaded when there is a request to feature module. To load a module lazily, useloadChildren
in route configuration as following.
const routes: Routes = [ { path: ‘user’, loadChildren: () => import('./user.module').then(mod => mod.UserModule) }, ------ ];
Q.16 : What is preloading of modules?
Ans : In preloading, feature modules are loaded asynchronously in background just after application start. For preloading, load module usingloadChildren
and configure preloadingStrategy
with RouterModule.forRoot()
.
1. Load module using
loadChildren
.
const routes: Routes = [ { path: ‘user’, loadChildren: () => import('./user.module').then(mod => mod.UserModule) }, ------ ];
preloadingStrategy
.
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
PreloadAllModules
strategy preloads all modules configured by loadChildren
. To preload only selective modules, we need to create custom preloading strategy.
Q.17 : How will you create custom preloading strategy?
Ans : To create custom preloading strategy, create a class by overridingPreloadingStrategy
abstract class that provides a preloading strategy. The built-in strategies are NoPreloading
and PreloadAllModules
. Find the code snippet to create a custom preloading strategy.
@Injectable() export class CustomPreloadingStrategy implements PreloadingStrategy { preload(route: Route, load: () => Observable<any>): Observable<any> { --------- } }
CustomPreloadingStrategy
in application module or feature module wherever required.
Q.18 : What route guards are used in Angular routing?
Ans : The route guards used in Angular routing are as following.interface Route { canActivate?: Array<CanActivateFn> canActivateChild?: Array<CanActivateChildFn> canDeactivate?: Array<CanDeactivateFn<any>> canMatch?: Array<CanMatchFn> resolve?: ResolveData }
Q.19 : What is canActivate
functional route guard and how will it work?
Ans : The canActivate
route guard handles if the current user is allowed to activate the component.
To use
canActivate
route guard, create a service that will contain a method to decide if the current user is allowed to activate the component. This will return boolean value. Create auth guard service as following.
@Injectable() export class MyAuthGuardService { canActivateRouteGuard(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { ------ } }
inject
method to get any required dependencies. Find the code to configure canActivate
functional route guard.
path: '', component: DashboardComponent, canActivate: [ (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => inject(MyAuthGuardService).canActivateRouteGuard(route, state) ], children: [ --------- ]
canActivateRouteGuard()
method returns true, the current user will be allowed to activate the component, otherwise not.
Q.20 : What is canActivateChild
functional route guard and how will it work?
Ans : The canActivateChild
route guard handles if the current user is allowed to activate a child of the component.
To use
canActivateChild
route guard, create a service.
@Injectable() export class MyAuthGuardService { canActivateChildRouteGuard(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { ------ } }
canActivateChild
functional route guard as following.
path: 'emp-list', component: EmpListComponent, canActivateChild: [ (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => inject(MyAuthGuardService).canActivateChildRouteGuard(route, state) ]
canActivateChildRouteGuard()
method returns true, the current user will be allowed to activate the child of the component, otherwise not.
Q.21 : What is canDeactivate
functional route guard and how will it work?
Ans : The canDeactivate
route guard handles if the current user is allowed to deactivate the component. To use The canDeactivate
, find the code snippet.
Create a service for route guard.
export interface CanComponentDeactivate { canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean; } @Injectable() export class RouteGuardService { canDeactivate(component: CanComponentDeactivate, state: RouterStateSnapshot) { --------- } }
canDeactivate
functional route guard.
path: 'add', component: AddUserComponent, canDeactivate: [ (component: CanComponentDeactivate, state: RouterStateSnapshot) => inject(RouteGuardService).canDeactivate(component, state) ]
canDeactivate()
method of RouteGuardService
returns true, then the current user is allowed to deactivate the component, otherwise not.
Q.22 : What is canMatch
functional route guard and how will it work?
Ans : The canMatch
route guard handles if the current user is allowed to match the Route
.
Q.23 : What is resolve
guard and how will it work?
Ans : The resolve
guard configures a map of DI tokens used to look up data resolvers. The router waits for the data to be resolved before the route is finally activated.
To use
resolve
guard, create a resolver.
@Injectable() export class UserDetailResolver { resolve(route: ActivatedRouteSnapshot): Promise<User | null> { --------- } }
path: 'detail/:user-id', component: UserDetailComponent, resolve: { personDetail: (route: ActivatedRouteSnapshot) => inject(UserDetailResolver).resolve(route) }
Q.24 : What is named router outlet and how is it created?
Ans : Named router outlet is used to open components in popup view. Named outlet stays open even when we switch between pages in our application. Named outlet is created using<router-outlet>
tag with name
attribute.
<router-outlet name="userPopup"></router-outlet>
{ path: 'update-user', component: UserUpdateComponent, outlet: 'userPopup' }
<a [routerLink]="[{ outlets: { userPopup: ['update-user'] } }]" >
null
.
Q.25 : How can you set the page title per route?
Ans : The page title per route can be set usingRoute.title
.
{ path: 'add', component: AddUserComponent, title: 'Add User’ }
/add
, title will be Add User.
Q.26 : How will you customize title using TitleStrategy
?
Ans : The TitleStrategy
is used to set the page title after a router navigation. It has three methods.
buildTitle() : Finds the existing title from
RouterStateSnapshot
.
getResolvedTitleForRoute() : Returns the final value of
Route.title
property.
updateTitle() : Updates the title.
Find the sample code to create custom
TitleStrategy
.
@Injectable() export class MyCustomTitleStrategy extends TitleStrategy { override updateTitle(routerState: RouterStateSnapshot) { const pageTitle = this.buildTitle(routerState); if (pageTitle !== undefined) { document.title = `ConcretePage - ${pageTitle}`; } else { document.title = `ConcretePage - Home`; } } }
MyCustomTitleStrategy
using provider in application module.
providers: [ {provide: TitleStrategy, useClass: MyCustomTitleStrategy} ]
Q.27 : What is difference between loadComponent
and loadChildren
?
Ans :
loadComponent : Loads a single component lazily on demand.
loadComponent: () => import('src/components/user-detail.component') .then(mod => mod.UserDetailComponent)
loadChildren: () => import('src/constants/app-routes.constant') .then(mod => mod.APP_ROUTES)
Q.28 : What is Route.providers
?
Ans : The Route
has providers
property to configure provider array for this route and its children.
path: 'user', component: UserComponent, providers: [ UserService ], children: [ --------- ]
UserService
is available to the path /user and its children.
Q.29 : What is path-matching strategy in routing?
Ans : The path-matching strategy decides whether the URL should match by prefix or full. The propertypathMatch
of Route
can have values either 'prefix' or 'full'. For the value ‘full’, entire URL is matched. It is useful in redirecting empty-path routes.
Q.30 : What is the role of UrlMatcher
in routing?
Ans : The UrlMatcher
is used to create custom URL matcher for Route.matcher
. The Route.matcher
cannot be used with Route.path
and Route.pathMatch
.
Q.31 : What is Route.outlet
?
Ans : In path configuration, outlet
property is assigned with RouterOutlet
object where the component can be placed when the path matches.
Q.32 : How can you pass data to routed components?
Ans : To pass data to routed components, we configureRoute.data
property in path configuration.
Q.33 : What is the use of RunGuardsAndResolvers
in routing?
Ans : The RunGuardsAndResolvers
is the policy for when to run guards and resolvers on a route. Use Route.runGuardsAndResolvers
property to configure RunGuardsAndResolvers
in routing.