Programmatical Routing
- Understand programmatic navigation
Learn how to trigger navigation from component code.
- Use Router service
Master the Angular Router service for programmatic navigation.
- Handle navigation events
Learn how to respond to navigation events in your components.
In the last step, you tested the form with this scenario:
- Click on the
Add a new task
link - Enter a title and description in the form
- Click on the
Create task
button - Click on the
Task List
link
But what if we want to redirect the user to the task list after submitting the form? This is a common scenario in web applications, and Angular provides a way to do it.
You’ve seen how to trigger navigation by clicking a link with the routerLink directive. But in this situation, you’ll trigger navigation when the submit function is called.
Inject the Router
Your own custom services aren’t the only things you can inject into a component’s constructor. Using the Angular Router functionality, you can inject the Router service into a component.
This service allows you to retrieve information about the current route and enables you to navigate to a different route.
-
Modify the file
src/app/task-form.component.ts
.task-form.component.ts import { Component } from "@angular/core";import { TaskService } from "../task.service";import { Router } from "@angular/router";@Component({selector: "app-task-form",templateUrl: "./task-form.component.html",styleUrls: ["./task-form.component.css"],})export class TaskFormComponent {task = {title: "",description: "",};constructor(private taskService: TaskService,private router: Router,) {}submit() {this.taskService.addTask(this.task);this.router.navigate(["/"]);}}
The navigation function expects an array of route segments as a parameter.
In our case, you’ll navigate to the tasks route as defined in your route configuration. Therefore, you pass ['/']
.
const routes: Routes = [ { path: "", component: TaskListComponent }, { path: "add-task", component: TaskFormComponent },];
Test it
Now, if you repeat the previous scenario:
-
Click on the
Add a new task
link -
Enter a title and description in the form
-
Click on the
Create task
button
You should be redirected to the task list.
In this chapter, you learned how to use programmatic routing in an Angular application. You learned how to inject the Router service into a component and use its navigate function to navigate to a different route.