Angular router navigate method example

In this tutorial, we are going to learn about how to navigate programmatically in the angular router by using a naviagte method.

In angular applications normally we use routerLink directive to navigate to different pages in our site but in some cases, we need to push the user to different routes based on the events like when a user clicks on a login button or form submission.

If you are new to angular then check out my previous tutorial Angular router beginners guide

The navigate method is imported from the @angular/router package which helps us to navigate a user programmatically.

Let’s see an example.

In this example, we are navigating a user to home page whenever submits a form.

contact.component.html
<form (submit)="onSubmit()">    <input placeholder="name" name="name" [(ngModel)]="user.name" />
    <input placeholder="email" name="email" [(ngModel)]="user.email" />
    <button type="submit">Submit</button></form>
contact.component.ts
import { Component} from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent {
  user = {
    name: '',
    email: ''
  };
  // injecting route object into this contact component
  constructor(private route: Router) { }
  onSubmit() {
     console.log(this.user.name, this.user.email);
    // inside array we need to pass the path we need to naviagte
    this.route.navigate(['/']);  }
}

In the above code, first, we imported Router from the @angular/router package and injected it into the ContactComponent constructor.

Inside the OnSubmit method we are accessing the navigate method from the this.route object and invoking the method by passing an array with the path ['\'].