Routing Angular Applications: Lesson 11 of 23

Route Navigation from a Component

Up Next

Recap

Autoplaying in 7 seconds!

Cancel

I

Table of Contents

    n 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

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.