Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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},
];

like image 290
Jeff M Palmer Avatar asked Nov 14 '25 22:11

Jeff M Palmer


2 Answers

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 :)

like image 101
Andriy Avatar answered Nov 17 '25 12:11

Andriy


You need to add RouterModule in app.component.ts, it is a module provided by Angular for routing functionality, like the example bellow

import { Component } from '@angular/core';
import { RouterModule, RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'main-frontend';
}
like image 31
BraCode Avatar answered Nov 17 '25 11:11

BraCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!