Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 5 routing is reloading the entire page

I'm having a problem with angular 5. I used a fresh install with angular cli : ng new Test --routing, but it seems to reload the entire page not only the part. Did someone had the same problem?

Routing module

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {GalleryComponent} from './gallery/gallery.component';
import {MainComponent} from './main/main.component';

const routes: Routes = [
    {
        path: '',
        component: MainComponent
    },
    {
        path: 'gallery',
        component: GalleryComponent
    }
];

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

Navigation code

<ul class="navbar-nav navbar-left">
  <li class="nav-item">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
   </li>
   <li class="nav-item">
       <a class="nav-link" href="/gallery">Galerie</a>
   </li>
</ul>
like image 793
M. Alexandru Avatar asked Mar 04 '18 11:03

M. Alexandru


1 Answers

You should try using routerLink instead of href attribute in your <a> tags.

<ul class="navbar-nav navbar-left">
  <li class="nav-item">
        <a class="nav-link" routerLink="/">Home <span class="sr-only">(current)</span></a>
   </li>
   <li class="nav-item">
       <a class="nav-link" routerLink="/gallery">Galerie</a>
   </li>
</ul>

A standard href will tell the browser to navigate to the given URL. But what you want is telling Angular to navigate to the URL.

like image 175
Noémi Salaün Avatar answered Oct 14 '22 15:10

Noémi Salaün