Now that the routes are set up, we need some way to actually change routes.
This example will show how to change routes using the template, but it is possible to change routes in TypeScript.
Here is one example (without binding):
<a routerLink="/home">Home</a>
If the user clicks on that link, it will route to /home
. The router knows how to handle /home
, so it will display the Home
Component.
Here is an example with data binding:
<a *ngFor="let link of links" [routerLink]="link">{{link}}</a>
Which would require an array called links
to exist, so add this to app.ts
:
public links[] = [
'home',
'login'
]
This will loop through the array and add an <a>
element with the routerLink
directive = the value of the current element in the array, creating this:
<a routerLink="home">home</a>
<a routerLink="login">login</a>
This is particularly helpful if you have a lot of links, or maybe the links need to be constantly changed. We let Angular handle the busy work of adding links by just feeding it the info it requires.
Right now, links[]
is static, but it is possible to feed it data from another source.