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>
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With