Jul 7, 2024
followers
page with URL /followers
profile
page with URL /profile/:username/:userId?foo
import { RouterModule } from '@angular/router';
RouterModule.forRoot(routes)
to define root/application-wide routesRouterModule.forChild(routes)
{ path: 'path', component: Component }
{ path: '', component: HomeComponent }
{ path: 'followers', component: FollowersComponent }
{ path: 'profile/:username', component: GithubProfileComponent }
{ path: 'posts', component: PostsComponent }
{ path: '**', component: NotFoundComponent }
app.component.html
<router-outlet></router-outlet>
<nav>...
<a [routerLink]="['/followers']">Followers</a>
<a [routerLink]="['/posts']">Posts</a>
</nav>
<router-outlet></router-outlet>
routerLink
directive instead of href
for SPAs to avoid re-download and page flicker
<a [routerLink]="['/posts']">Posts</a>
<a [routerLink]="['/profile', username]">Profile</a>
routerLinkActive
for adding CSS class to active links
<li [routerLinkActive]="'active current'">
<a [routerLink]="['/followers']">Followers</a>
</li>
<li [routerLinkActive]="'active current'">
<a [routerLink]="['/posts']">Posts</a>
</li>
ActivatedRoute
service
constructor(private route: ActivatedRoute) {}
this.route.paramMap.subscribe(params => {...})
params.get('paramName')
to access specific parametersthis.route.paramMap.subscribe(params => {
this.userId = +params.get('id');
});
routerLink
for navigation without page reloadsActivatedRoute
routerLink
routerLinkActive
used for dynamic application of CSS classes based on active route