Video Course

Routing Angular v2+ Applications: Lesson 11 of 23

Route Navigation from a Component

Up Next

Recap

Autoplaying in 7 seconds!

Cancel

In addition to routerLink, we are able to navigate from inside our class.

We can use the Router that comes from @angular/router. Once we inject it into our class, we can use this.router.navigate(['/about', user.username]);

import { Router } from '@angular/router';

...

export class AboutUserComponent implements OnInit {
  user: User;

  constructor(
    private route: ActivatedRoute, 
    private service: UserService,
    private router: Router
  ) {}

  ngOnInit() {
    // grab the current username
    let username = this.route.snapshot.params['username'];
    this.service.getUser(username).then(user => this.user = user);
  }

  goBack() {
    this.router.navigate(['/about']);
  }

}

Chris Sevilleja

162 posts

Co-founder of Scotch.io. Slapping the keyboard until something good happens.