Skip to content

Programmatical routing

  • βœ”οΈ
    Trigger the route programmatically
    Learn how to trigger a route programmatically 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 a description in the form
  3. Click on the Create task button
  4. Click on the List of tasks link

But what if you want to redirect the user to the list of tasks after the form is submitted? That’s a common scenario in web applications, and Angular provides a way to do that.

You saw how to trigger a navigation by clicking on a link with the routerLink directive. But in our situation, you want to trigger a navigation when the createTask function is called.

Inject the Router

Your TaskService service is not the only element you can inject in the constructor of a component. By using the Angular Router feature, you can inject the Router service in a component.

This service provides information about the current route and allows you to navigate to a different one.

πŸŽ“ Instructions

  1. Update the src/app/task-form.component.ts file.

    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 implements OnInit {
    task = {
    title: '',
    description: ''
    };
    constructor(
    private taskService: TaskService,
    private router: Router
    ) { }
    ngOnInit() {}
    createTask() {
    this.taskService.addTask(this.task);
    this.router.navigate(['/']);
    }
    }

The navigate function expects an array of route segments as a parameter. In our case, you want to navigate to the tasks route as you defined it in our route definition, so you use ['/'];

const routes: Routes = [
{ path: '', component: TaskListComponent },
{ path: 'add-task', component: TaskFormComponent }
];

Let’s test it out

Now if you repeat the previous scenario:

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

You should be redirected to the list of tasks.

βœ”οΈ What you learned

In this chapter, you learned how to use programmatical routing in an Angular application. You learned how to inject the Router service in a component and use its navigate function to navigate to a different route.