Home > Software engineering >  Angular 14: App not routing even though path changes in the URL
Angular 14: App not routing even though path changes in the URL

Time:09-26

I am setting up a basic angular website and my routing does not appear to be working.

I have a app.component.html page (acting currently as my Home page):


        <li >
          <a  [routerLink] = "['']">Home</a>
        </li>
        <li >
          <a  [routerLink] = "['login']" >Login</a>
        </li>
        <li >
          <a  [routerLink] = "['register']" routerLinkActive = "active" >Register</a>
        </li>

I then have a login and register component, very basic:

Login

and

Register

They are both included in my authModule:

import {NgModule} from "@angular/core";
import {CommonModule} from "@angular/common";
import {LoginComponent} from "../components/login/login.component";
import {RegisterComponent} from "../components/register/register.component";

@NgModule({
  declarations: [
    LoginComponent,
    RegisterComponent
  ],
  imports: [
    CommonModule
  ],
  exports : [
    LoginComponent,
    RegisterComponent
  ]
})
export class AuthModule { }


Then this is my app.module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {AuthModule} from "./auth/auth/auth.module";

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AuthModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


and finally my app-routing.module:

import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {LoginComponent} from "./auth/components/login/login.component";
import {RegisterComponent} from "./auth/components/register/register.component";
import {AppComponent} from "./app.component";

const routes: Routes = [
  {path: "", component: AppComponent, pathMatch: 'full'},
  {path: 'login', component: LoginComponent},
  {path: 'register', component: RegisterComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

When the app loads, it shows http://localhost:4200/ and correctly show my home page.

But when I click the Login button the url changes to:

http://localhost:4200/login

but does not change the content on the page.

I am wondering if anyone can help.

Thank You :)

CodePudding user response:

Do you have <router-outlet></router-outlet> on the root page? I think you are missing this.

You can read more about it here: https://angular.io/api/router/RouterOutlet

  • Related