Programmatic Navigation in Angular
You can navigate to URLs not only using links, but also inside JavaScript code, using special commands.
This is done using the Router
service. Let's see how to work with it. First, import it:
import { Router } from "@angular/router";
Now let's inject it into the component using dependency injection:
export class AppComponent {
constructor(private router: Router) {
}
}
The service has a method navigate
, which goes to a given URL. Let's use this method:
export class AppComponent {
constructor(private router: Router) {
}
go() {
this.router.navigate(['/aaaa/']);
}
}
Now let's call the go
method by pressing the button:
<button (click)="go()">btn</button>
Make two buttons. Let the first one take you to one URL, and the second one to another.