简体   繁体   中英

Angular routerLink in Navbar is not working

I am following a tutorial and building my first Angular app (yay.). I have followed all the steps but cannot seem to find my issue. I am adjusting all of the href links in the navbar to be routerLink links. I just tried to change the "Background" link and it isnt working. I literally have tried even copy and pasting straight from the the Angular CLI website, but it still isn't working. Any help would be greatly appreciated.

Here is my app-routing.module.ts file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { AccomplishmentsComponent } from './accomplishments/accomplishments.component';
import { AdditionalInformationComponent } from './additional-information/additional-information.component';
import { BackgroundComponent } from './background/background.component';
import { IntroComponent } from './intro/intro.component';
import { SkillsComponent } from './skills/skills.component';


const routes: Routes = [
  { path: '', component: IntroComponent },
  { path: 'about', component: AboutComponent },
  { path: 'accomplishments', component: AccomplishmentsComponent },
  { path: 'additional-information', component: AdditionalInformationComponent },
  { path: 'background', component: BackgroundComponent },
  { path: 'intro', component: IntroComponent },
  { path: 'skills', component: SkillsComponent },
];

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

And here is my index.html file:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Garbage Coder | Software Engineer</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Garbage Coder</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
          <div class="navbar-nav">
            <a class="nav-item nav-link active" href="#">Home <span class="sr-only">(current)</span></a>
            <a class="nav-item nav-link" href="#">About</a>

                                                              <!--Issue is here-->
            <a class="nav-item nav-link" [title]="Background" [routerLink]="['/background']">Background</a>


            <a class="nav-item nav-link" [title]="Skills" href="#">Skills</a>
            <a class="nav-item nav-link" href="#">Accomplishments</a>
          </div>
        </div>
      </nav>
  <app-root></app-root>
  <router-outlet></router-outlet>
</body>
</html>

I've gone through your stackblitz demo. And found out that even if I type the url's to the components directly to the bar, it doesn't navigate.

I then checked the app module for the route configuration, and found out that you have mistake there.

const appRoute: Route = [
  { path: 'about', component: About },
  { path: 'service', component: Service },
  { path: 'dashboard', component: Dashboard, canActivate: [] }
]

This should be changed like Route become Routes

const appRoute: Routes = [
  { path: 'about', component: About },
  { path: 'service', component: Service },
  { path: 'dashboard', component: Dashboard, canActivate: [] }
]

import from here,

import { Routes } from '@angular/router';

try it and let me know.

-----Edits------

Additional to this, you have multiple router outlets (one in app component html and other in the index.html), which isn't allowed in angular unless at least one of them is a named router outlet. Seems like these are the issues. And I strongly suggest you to keep the index.html file as it is when the initial project was generated by angular-cli. Write your code from app-component onwards to the child components.

Another one issue is you are not rendering the app component to the dom as you have changed the selector of app component from app-root to my-app but still using the tag app-root to render app component in index.html. Update that one as well, so that the app-component is rendered.

After rewatching my tutorial, I discovered that the issue was my navbar needed to be inside the app.component.html instead of my index.html as @RamChandraNeupane suggested in the comments. Thank you everyone for your help!

try it like this routerLink="background" remove the "/" and both square brackets

Try this, you have to remove the brackets...        
<div class="pl-20">
          <a class="color-grey2 font-14" routerLink="/transformer-management" routerLinkActive="active">
            <span>Transformers</span>
           </a>
       </div>
       <div class="pl-20">
         <a class="color-grey2 font-14" routerLink="/cost-file-management" routerLinkActive="active">
      <span>Costs</span>
    </a>
      </div>

My Stackblitz forked from yours

As @AnzalKhan mentioned, the routes should be of type 'Routes' not 'Route'.

Also in your stackblitz, there was no background component, hence I navigated to about component on click of Background in the nav bar. There were no other routing mistakes. But as a best practice, you should not edit your index.html and the template logic should start in app component. I have cut and paste the nav bar and router outlet to the app.component.html.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM