Questions
How do you do routing in Angular?
The Scenario
You are a frontend engineer at a social media company. You are building a new single-page application (SPA) that will have multiple pages, such as a home page, a profile page, and a settings page.
You need to find a way to handle the routing between these pages.
The Challenge
Explain how you would do routing in Angular. What is the Angular Router, and what are the key features of it?
A junior engineer might try to solve this problem by using a series of `*ngIf` statements to show and hide the different pages. This would not be a very scalable or maintainable solution.
A senior engineer would know that the Angular Router is the perfect tool for this job. They would be able to explain what the Angular Router is and how to use it to handle the routing between the different pages.
Step 1: Understand What the Angular Router Is
The Angular Router is a powerful router that is built and maintained by the Angular team. It allows you to map URLs to components, so that you can build a single-page application with multiple pages.
Step 2: The Key Features of the Angular Router
| Feature | Description |
|---|---|
| Nested Routes | You can nest routes inside other routes to create complex layouts. |
| Dynamic Routes | You can use dynamic segments in your routes to match a pattern, such as /user/:id. |
| Route Guards | You can use route guards to protect routes from unauthorized access. |
| Lazy Loading | You can lazy load modules to improve the performance of your application. |
Step 3: Set Up the Angular Router
Here’s how we can set up the Angular Router in our application:
1. Import the RouterModule:
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent },
{ path: 'settings', component: SettingsComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }2. Add the <router-outlet> component to your template:
The <router-outlet> component is where the component for the current route will be rendered.
<router-outlet></router-outlet>3. Use the routerLink directive to navigate between routes:
<a routerLink="/">Home</a>
<a routerLink="/profile">Profile</a>
<a routerLink="/settings">Settings</a> Practice Question
You want to protect a route so that it can only be accessed by authenticated users. Which of the following would you use?