In the app's current state, the entire page refreshes when we click on an internal link that exists within the app. While this may not seem significant with a small app, this can have performance implications for larger pages with more content where users have to redownload assets and run calculations again.
In this activity, you'll learn how to leverage the RouterLink
directive to make the most use of Angular Router.
-
Import
RouterLink
directiveIn
app.component.ts
add theRouterLink
directive import to the existing import statement from@angular/router
and add it to theimports
array of your component decorator....import { RouterLink, RouterOutlet } from '@angular/router';@Component({ standalone: true, imports: [RouterLink, RouterOutlet], ...})
-
Add a
routerLink
to templateTo use the
RouterLink
directive, replace thehref
attributes withrouterLink
. Update the template with this change.import { RouterLink, RouterOutlet } from '@angular/router';@Component({ ... standalone: true, template: ` ... <a routerLink="/">Home</a> <a routerLink="/user">User</a> ... `, imports: [RouterLink, RouterOutlet],})
When you click on the links in the navigation now, you should not see any blinking and only the content of the page itself (i.e., router-outlet
) being changed 🎉
Great job learning about routing with Angular. This is just the surface of the Router
API, to learn more check out the Angular Router Documentation.