Angular Routing
Angular routing is a powerful feature that allows you to navigate between different views or components in your Angular application. It enables you to create single-page applications (SPAs) where the content changes dynamically without reloading the entire page.
setup
When an Angular app is created, the Angular CLI automatically sets up routing for you.
Routing is set up in app.config.ts
. The routes are imported and passed to the provideRouter
function.
1 | import { routes } from './app.routes'; |
app.routes.ts
is where you define your routes. The Routes
type is imported from @angular/router
, and the routes are defined as an array of objects. Each object represents a route and contains properties such as path
and component
.
1 | import { Routes } from '@angular/router'; |
Adding Routes
Create components profile and about using the Angular CLI:
1 | ng generate component home |
In app.routes.ts
, import the components and add them to the routes array:
1 | import { Routes } from '@angular/router'; |
The two asterisks, ** indicate to Angular that this routes definition is a wildcard route.
Router Outlet
The <router-outlet>
element informs Angular to update the application view with the component for the selected route.
1 | <router-outlet /> |
Getting Query Parameters
To access query parameters in Angular, you can use the ActivatedRoute
service. This service provides access to information about a route associated with a component that is loaded in an outlet.
1 | import { inject } from '@angular/core'; |
Now you can inject the ActivatedRoute
service into your component and access the query parameters.
1 | private readonly route = inject(ActivatedRoute); |
RouetrLink
To navigate between routes in Angular, you can use the routerLink
directive. This directive allows you to bind a link to a specific route.
1 | <a [routerLink]="['/todo-list']">Todo List</a> |
RouterLinkActive
The routerLinkActive
directive is used to add a CSS class to an element when the associated route is active. This is useful for styling navigation links based on the current route.
1 | <a [routerLink]="['/todo-list']" routerLinkActive="active">Todo List</a> |
Router Navigation
To programmatically navigate to a route in Angular, you can use the Router
service. This service provides methods for navigating to different routes in your application.
1 | import { Router } from '@angular/router'; |
Lazy Loading
Lazy loading is a technique in Angular that allows you to load feature modules on demand, rather than loading them all at once when the application starts. This can significantly improve the initial load time of your application.
1 | { |