Skip to content

Advanced Routing

Chapter Objectives

  • ✔️
    Advanced Routing
    Learn how to use advanced routing in an Angular application.

In the last step, you tested the form with this scenario:

  1. Click on the Add a new task link
  2. Enter a title and description in the form
  3. Click on the Create task button
  4. 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.

🎓 Instructions

  1. 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:

  1. Click on the Add a new task link
  2. Enter a title and description in the form
  3. Click on the Create task button

You should be redirected to the task list.

✔️ What you’ve learned

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.