Search code examples
angularbrowserurl-routing

Angular 8 Routing: Changing URL doesn't navigate to expected page


I'm creating a simple Angular project with two components: home and submit. My app-routing.module.ts look like this:

import { NgModule } from '@angular/core';
import { Routes, RouterModule, ActivatedRoute } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { SubmitComponent } from './submit/submit.component';


const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'submit', component: SubmitComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

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

In my browser if I change the path to /submit the page looks like it reloads and then defaults back to /home. I have already tried changing the path: '' to path: '**'. It does not navigate to the submit component. Any ideas what I am doing incorrectly?

Angular 8.2.14 Google Chrome


Solution

  • There isn't anything wrong with your routing configuration. We don't have enough information to help you pinpoint your issue beyond that.

    When I am approached with this question, it's usually one of the following problems:

    1. Missing <base href="/"> in your index.html head element

    2. Not importing AppRoutingModule into your AppModule

    3. Missing <router-outlet></router-outlet> element in parent component

    I saw in the comments that you have the <base href="/"> in your index.html file so we'll forget that one for now.

    From here:

    Check to make sure you're importing your AppRoutingModule in your App.Module.ts file.

    If that's not the issue, make sure you have a <router-outlet></router-outlet> element in your parent component (probably your app.component.html based on the simplicity of your app). The Angular router searches your routes for one that matches the URI and injects an instance of the component specified in your routing configuration into the closest router-outlet that is higher up in the component tree. In other words, if there is no router-outlet, the Angular router doesn't know where to render the component you specified in your routing configuration.

    If neither of those solve your problem, try posting more information so we can help further. It would be helpful to see your app.module.ts and app.component.html files at a minimum. Alternatively, try recreating your app in a stackblitz and posting the link.