Before someone marks this question duplicate, i have tried the following questions:
Angular 5 router.navigate does not work
router.navigate is not working (Angular6, lazy loading)
router navigate doesn't redirect to other page
I tried the solutions given the these questions and nothing worked. So i came here to ask my own question. Now to the question:
I have created a new app where i am trying to route to Home.Component
from the App.Component
with router.navigate()
. Below are the files for reference:
App Component.html
<p>App component works</p>
<button (click)="onClick()">Click Home</button>
App.component.ts
import { Router, ActivatedRoute } from '@angular/router';
export class AppComponent {
constructor(private router:Router){}
onClick(){
console.log("Button clicked!!");
this.router.navigate(['home']);
}
}
app-routing.module.ts
const routes: Routes = [
{ path:'', component: AppComponent, pathMatch:'full'},
{path:'home', component:HomeComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
@NgModule({
declarations: [
AppComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I am not understanding why the home.component.html
is not loading when clicking the Click Home
button.
Also, i tried creating another component Second.component
and tried loading the same from the Home.component
on button click(button inside the Home.component
).
The components are not lazy-loaded(they are in the same module). Whenever i click the button, the url changes. So why doesn't the associated component load? Have i missed some part of the configuration? Here is the demo