Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 722
Bonfry Avatar asked Dec 11 '22 05:12

Bonfry


2 Answers

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.

like image 70
Lazar Ljubenović Avatar answered Dec 26 '22 19:12

Lazar Ljubenović


Using href will perform URL redirection on that anchor tag, the redirection does happen on the same(since considered target='_self' on anchor).

Use routerLink directive provided by Angular Router API, which helps to navigate between the SPA pages.

<a routerLink="/page1">Page1</a>     
<a routerLink="/page2">Page2</a>
like image 35
Pankaj Parkar Avatar answered Dec 26 '22 17:12

Pankaj Parkar