What am I missing on a Basic Angular 17 to get Routing for an SPA to work?

2.2k Views Asked by At

Why won't my 'routerLink' items navigation work?
It's a new project based on the only changes:

ng new -S --routing home2

app.component.html

<div style="cursor: pointer;"><a routerLink="/page1" routerLinkActive>Page 1</a></div>&nbsp;
<div style="cursor: pointer;"><a routerLink="/page2" routerLinkActive>Page 2</a></div>&nbsp;

<router-outlet></router-outlet>

app.routes.ts

import { Routes } from '@angular/router';
import { Page1Component } from './components/page1/page1.component';
import { Page2Component } from './components/page2/page2.component';

export const routes: Routes = [
    {path: 'page1', component: Page1Component},
    {path: 'page2', component: Page2Component},
];

1

There are 1 best solutions below

0
Andriy On

After running ng new -S --routing home2, angular just prepares an infrastructure for using router. You need then to add:

  • router config (as you already did)
  • router links if needed (as you already did)
  • add missing imports (as Yong Shun already mentioned) in you app component, in your case you should add RouterLink and RouterLinkActive (or just RouterModule instead of three directives):
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink, RouterLinkActive],
  templateUrl: './app.component.html',
  styleUrl: './app.component.less'
})

after adding missing imports your routes should work

Also, you should pass one or several CSS classes to routerLinkActive directive.

For your future questions I would recommend to reproduce your issue using Angular project on STACKBLITZ, this way it will be much easier for others to help you. GOOD LUCK with NG17 :)