Angular 4+: RouterLink in <a> element not working properly
Asked Answered
M

5

6

I have placed my AppRoutingModule inside imports of @NgModule of AppModule class.

AppRoutingModule is defined in such way:

const APP_ROUTES : Routes = [
    { 
        path: '', 
        redirectTo: 'home', 
        pathMatch: 'full',
    },
    {
        path: 'home', 
        component: HomeComponent
    },
    {
        path: 'lesson-offers', 
        component: LessonOffersComponent
    },

    { path: '**', redirectTo: 'home' }
]

I have placed <router-outlet></router-outlet> in the app.component.html.

Pages displays correctly based on URLs:

localhost:5000/  
localhost:5000/home  
localhost:5000/lesson-offers

The problem is in my header.component.ts where I am trying to add routerLink to home page. I have tried such solutions:

<img routerLink="home" ... />
<img [routerLink]="/home" ... />
<a routerLink="home"> <img ... /></a>
<a [routerLink]="home" ... ><img ... /></a>

Firstly when I placed routerLink in <img> element such directive hasn't been found. Then in <a> element it makes casual <a href="/home"> from routerLink and makes full page reloading ! Shouldn't it reload only content of <router-outlet>?

Maybe it has some meaning that my layout looks like this:

// AppComponent HTML
<header-bar></header-bar>
<router-outlet></router-outlet>

and routerLink is placed on element in children component <header-bar> (logo) and should navigate on <router-outlet> in its parent?

But I have also tested this behaviour using routerLinks placed directly inside AppComonent and nothing has changed! RouterLink still reloads the webpage!:

<header-bar></header-bar>
<a routerLink="home">Home</a> 
<a routerLink="lesson-offers">Lesson Offers</a>
<a routerLink="page-not-found">Not Exsists</a>
<router-outlet></router-outlet>
Mudstone answered 6/5, 2017 at 9:19 Comment(7)
Do you have RouterModule imported into module which contains header.component ?Costermansville
Have you read through the routing tutorial?Genisia
<a [routerLink]="['/a4']"></a> try something like thisWarrior
you can also ensure that base href is properly set.Wheatworm
I have this <base href="/" /> in HTML head section when I show page source.Keeleykeelhaul
I have also tired something like this: <a [routerLink]="['/home']">Home</a> and the page also reloadsKeeleykeelhaul
Should browser reload button blink? How to simulate whether entire page reloads? Add some timeout into header component or app component?Keeleykeelhaul
L
2

You need more to make routing work. Here is how your AppRoutingModule file should look like

import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { HomeComponent, LessonOffersComponent } from somewhere;

const APP_ROUTES : Routes = [
    { 
        path: '', 
        redirectTo: 'home', 
        pathMatch: 'full',
    },
    {
        path: 'home', 
        component: HomeComponent
    },
    {
        path: 'lesson-offers', 
        component: LessonOffersComponent
    },

    { path: '**', redirectTo: 'home' }
]

@NgModule({
  imports: [ RouterModule.forRoot(APP_ROUTES) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
Leery answered 6/5, 2017 at 10:23 Comment(8)
I have such a code I shortened it and not included class definition. Routing works i.e.Keeleykeelhaul
When I type: localhost:5000/lesson-offers it redirects correctly. But links made with usage of routerLink="" seems to make entire page reload.Keeleykeelhaul
I think that page is entirely reloaded cause web browser reload indicator is activating and changing to "X" buttonKeeleykeelhaul
Because your route config specifies a redirect when the path matches '' an empty string exactlyLeery
A redirect causes browser to reload the page to navigate to the specified urlLeery
When the path matches lesson-offers, angular downloads the component associated with that route path and insert right after the outlet, it does not reload the page as specified in your routing configLeery
yeah but I have specified routeLink like in my above post: i.e. routerLink="home" so it should match path:'home' and choose appropriate component.Keeleykeelhaul
Move the path: '' just above the path: '**' and beneath everything elseLeery
R
1

For anyone else having this issue, try this:

<a [routerLink]="['/home']" ... ><img ... /></a>

instead of this:

<a [routerLink]="home" ... ><img ... /></a>
Rodge answered 8/4, 2020 at 12:44 Comment(0)
I
1

To solve this problem, Need to import RouterModule module in header.Component.ts imported module. That means this component of parent module. Then run the CLI command ng serve

For Example:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';

import { HeadComponent } from './head/head.component';


@NgModule({
  declarations: [HeadComponent],
  imports: [
    CommonModule,
    RouterModule,

  ],
  exports: [
    CommonModule,
    HeadComponent
  ]
})
export class LayoutModule { }

This solution worked for my Angular 10 application

Ingeringersoll answered 12/6, 2021 at 3:10 Comment(0)
M
0

Ok I actually found the error and it was in the place that I have never ever will suppose. There was also other different behaviours like not working (click) event bindings. So I go across configurations of my web project which is base upon this sample angular 4 universal spa from github: https://github.com/MarkPieszak/aspnetcore-angular2-universal

  1. I have made upgrade from ASP NET Core SPA that was generated with yeoman tool.

npm install -g yo generator-aspnetcore-spa

Then, cd to an empty directory where you want your project to go, and then run Yeoman as follows:

yo aspnetcore-spa
  1. Then I have noticed that there isn't possible to easily use Leaflet Open Street Maps while using server-side pre-rendering.

  2. So made this upgrade from Angular 2+ -> Angular 4+, buy modifying each files configuration, module, boot, webpack, tsconfig, etc. file. I really was under big impression of this starter project under github:
    https://github.com/MarkPieszak/aspnetcore-angular2-universal

  3. At the end of the day I noticed that I remain some old code that I suppose that will be running correctly:

// boot.client.ts 
platform.destroy();
    });
} else {
    enableProdMode();
}

// Boot the application, either now or when the DOM content is loaded
const platform = platformUniversalDynamic();
const bootApplication = () => { platform.bootstrapModule(AppModule); };
if (document.readyState === 'complete') {
    bootApplication();
} else {
    document.addEventListener('DOMContentLoaded', bootApplication);
}

And the correct one in the new version of angular universal project that looks similar should be:

 modulePromise.then(appModule => appModule.destroy());
    });
} else {
    enableProdMode();
}

const modulePromise = 
 platformBrowserDynamic().bootstrapModule(BrowserAppModule);

PS. Previously I also made replacement of platformUniversalDynamic => platformBrowserDynamic.

Mudstone answered 6/5, 2017 at 21:56 Comment(0)
O
0

After many years passed from last answer, I didn't easily find correct answer. Also, I observed some erroneous answer. Therefore I want to added clear description about the usage of the routerlink in the HTML file of component for Angular 8++. After adding router paths to routingmodule , in order to use this routes in angular component:

  1. Import RouterModule to which module component have been declared
  2. Set route to routerLink in the HTML. Because of case sensitivity of the routerLink, be cautious not to use routerlink.

don't need adding nav-link class or import router to your component.

Oniskey answered 13/4, 2020 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.