Search code examples
angularangular-routing

Disable reloading page angular 6 routing


I have a problem with Angular. When I click to a link, browser reload site (Angular normally load only component which is connect with the path ). What I have to do?

Page1 and Page2 are default components.

app.module.ts:

import {RouterModule, Routes} from '@angular/router';
import { Page1Component } from './page1/page1.component';
import { Page2Component } from './page2/page2.component';

const routes: Routes = [
  { path: 'page1', component: Page1Component },
  { path: 'page2', component: Page2Component }
];

@NgModule({
  declarations: [
    AppComponent,
    Page1Component,
    Page2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }   

app.component.ts:

<router-outlet></router-outlet>
<a href="/page1">Page1</a>     
<a href="/page2">Page2</a>

Solution

  • The idea behind a single-page application is that the browser never triggers a request for another .html page, after fetching the initial index.html. Front-end navigation, enabled by Angular's @angular/router only imitates "pages".

    When you open a new Angular "page", JavaScript is executed which deletes the currently visible elements from the DOM and replaces them with new ones, which form a different-looking screen -- which we call "page".

    Using href on an anchor element (<a>), you're telling browser to fetch another page from the server. Instead, you should tell Angular to replace the DOM elements in order to form a new screen. You do this by using routerLink directive, which is available in RouterModule.

    <a routerLink="/page1">Go to page 1</a>
    

    I suggest reading through the "Tour of Heroes" tutorial available on angular.io, the official Angular website. It covers routing as well. Routing is also covered here.