Issue
My simple Angular Single Page application has two components. I have defined a route for each of these components. If I click on a link, corresponding component should be displayed in the view.
Router
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CompAComponent } from './comp-a/comp-a.component';
import { CompBComponent } from './comp-b/comp-b.component';
const routes: Routes = [
{
path: 'componentA', component: CompAComponent
},{
path: 'componentB', component: CompBComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
HTML
<div class="main-container">
<div class="nav-container">
<ul>
<li><a href="testApp/componentA">componentA</a></li>
<li><a href="testApp/componentB">componentB</a></li>
</ul>
</div>
<div class="component-container">
<router-outlet></router-outlet>
</div>
</div>
App.Module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CompAComponent } from './comp-a/comp-a.component';
import { CompBComponent } from './comp-b/comp-b.component';
@NgModule({
declarations: [
AppComponent,
CompAComponent,
CompBComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This application is working but every time I click on a link, it is fetching all the JS files from the server. Shouldn't a single page application get all the required files from server during initial loading?
I added 'testApp' in the href since this application has a context path of 'textApp' in the head of index.html file like <base href="/testApp">

Solution
Angular needs to do some stuff behind the scenes to tell the browser how to handle links within the SPA. So you should use the attribute routerLink on your links instead of href so Angular knows which links are SPA-links.
<div class="main-container">
<div class="nav-container">
<ul>
<li><a routerLink="/componentA">componentA</a></li>
<li><a routerLink="/componentB">componentB</a></li>
</ul>
</div>
<div class="component-container">
<router-outlet></router-outlet>
</div>
</div>
More info: https://angular.io/guide/router-tutorial#control-navigation-with-ui-elements
Answered By - kalleguld
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.