Navigating with routerLinks in Angular 9

Navigating around a single page application is a fundamental task, and Angular offers you a built-in directive, routerLink, to accomplish this.

Begin with the application setup assembled in the Setting up yor application. Your goal is to add an additional route to this application accompanied by a component; also, you want to be able to navigate between them using links.

Let’s Start

To begin, create another component, ArticleComponent, and an associated route:

[app/article/article.component.ts] 
 
import {Component} from '@angular/core'; 
 
@Component({ 
  template: 'Article component!' 
}) 
export class ArticleComponent {} 

Next, install an article route accompanied by this new component in app/app.module.ts:

 
import {NgModule} from '@angular/core'; 
import {BrowserModule} from '@angular/platform-browser'; 
import {RouterModule, Routes} from '@angular/router'; 
import {HomeComponent} from './home.component'; 
import {DefaultComponent} from './default.component';  
import {ArticleComponent} from './article.component'; 
 
const appRoutes:Routes = [ 
  {path: 'article', component: ArticleComponent}, 
  {path: '**', component: DefaultComponent} 
]; 
 
@NgModule({ 
  imports: [ 
    BrowserModule, 
    RouterModule.forRoot(appRoutes) 
  ], 
  declarations: [ 
    DefaultComponent, 
    ArticleComponent, 
    HomeComponent 
  ], 
  bootstrap: [ 
    HomeComponent 
  ] 
}) 
export class AppModule {} 

With the routes defined, you can now build a rudimentary navbar comprised of routerLinks. The markup surrounding the <router-outlet> tag will remain irrespective of the route, so the Home app component seems like a suitable place for the nav links.

The routerLink directive is available as part of RouterModule, so you can go straight to adding some anchor tags in app/home.component.ts:

import {Component} from '@angular/core'; 
 
@Component({ 
  selector: 'home', 
  template: ` 
    <h1>Home component</h1> 
    <a [routerLink]="['']">Default</a> 
    <a [routerLink]="['article']">Article</a> 
    <router-outlet></router-outlet> 
  ` 
}) 
export class HomeComponent {} 

How the above code Works?

At a high level, this is no different than the behavior of a vanilla href attribute. After all, the routes behave in the same way and are structured similarly. The important difference here is that using a routerLink directive instead of href allows you to move around your application the Angular way, without ever having the anchor tag click interpreted by the browser as a non-Angular navigation event.

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending