The companion to using routerLink
inside the template to navigate is doing it from inside JavaScript. Angular exposes the navigate()
method from inside a service, which allows you to accomplish exactly this.
The code, links, and a live example of this are available at .
Begin with the application that exists at the end of the How to do it... section of the Navigating with routerLinks recipe.
Your goal is to add an additional route accompanied by a component to this application; also, you wish to be able to navigate between them using links.
Instead of using routerLink
, which is the most sensible choice in this situation, you can also trigger a navigation using the Router
service. First, add nav
buttons and attach some empty click handlers to them:
[app/root.component.ts] import {Component} from '@angular/core'; @Component({ selector: 'root', template: ` <h1>Root component</h1> <button (click)="visitDefault()">Default</button> <button (click)="visitArticle()">Article</button> <router-outlet></router-outlet> ` }) export class RootComponent { visitDefault():void {} visitArticle():void {} }
Next, import the Router
service and use its navigate()
method to change the page location:
[app/root.component.ts] import {Component} from '@angular/core'; import {Router} from '@angular/router'; @Component({ selector: 'root', template: ` <h1>Root component</h1> <button (click)="visitDefault()">Default</button> <button (click)="visitArticle()">Article</button> <router-outlet></router-outlet> ` }) export class RootComponent { constructor(private router:Router) {} visitDefault():void { this.router.navigate(['']); } visitArticle():void { this.router.navigate(['article']); } }
With this addition, you should be able to navigate around your application in the same way you did before.
The Router
service exposes an API with which you can control your application's navigation behavior, among many other things. Its navigate()
method accepts an array-structured route, which operates identically to the Arrays bound to routerLink.
Obviously, this is an utter antipattern for building applications that are designed to scale. In this scenario, routerLink is a much more succinct and effective choice for building a simple navbar. Nevertheless, the Router service is an equally effective tool for traversing an Angular application's route structure.