Using RouterLink in Angular Standalone Components

Ole Ersoy
1 min readMay 23, 2023

--

Image by Rudy and Peter Skitterians from Pixabay

Scenario

We want to route to view2 like this.

   <button routerLink="/view2">
Go to View 2
</button>

Approach

Import RouterLink and add it to the imports array of the decorator of the component doing the routing, shown here from the main app component in the below demo.

import 'zone.js/dist/zone';
import { Component } from '@angular/core';
import {} from '@angular/common';
import { NgFor, NgIf, AsyncPipe, CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppNavComponent } from './app-nav.component';
import { AppView1Component } from './view1.component';
import { AppView2Component } from './view2.component';
import { provideRouter, Route, RouterLink } from '@angular/router';

export const routes: Route[] = [
{
path: '',
component: AppView1Component,
},
{
path: 'view2',
component: AppView2Component,
},
{
path: '**',
redirectTo: '',
},
];
@Component({
selector: 'my-app',
standalone: true,
imports: [NgFor, NgIf, AsyncPipe, AppNavComponent, RouterLink],
template: `
<h1>Hello from {{name}}!</h1>
<button routerLink="/view1">
Go to View 1
</button>
<button routerLink="/view2">
Go to View 2
</button>
<app-nav></app-nav>
`,
})
export class App {
name = 'Angular';
}

bootstrapApplication(App, {
providers: [provideRouter(routes)],
});

Demo

--

--

Ole Ersoy
Ole Ersoy

Written by Ole Ersoy

Founder of Firefly Semantics Corporation

No responses yet