I am working on Angular 6 lazy loading and stuck in a problem.
I have a sign in page that I can load on starting on the application after signing in there is a home page having a single select drop down with two options on select on first option Firstcomponent will load (First component have some info) and on select on second option SecondComponent will load (Second component also have some info) under select dropdown.
Now my problem is when refresh on that page i.e http://localhost:4300/home/first after refresh select dropdown and first component load as same but select dropdown field is shown blank here and want to selected with first option. Is there any solution for this?
Here is my code:
app.routing.module.ts
const routes: Routes = [
{
path: "",
redirectTo: "/signIn",
pathMatch: 'full'
}, {
path: "signIn",
component: SignInComponent
}, {
path: "home",
loadChildren: () => HomeModule
}, {
path: "**",
redirectTo: "/signIn",
pathMatch: 'full'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
app.module.ts
@NgModule({
declarations: [
AppComponent,
SignInComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HomeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
HomeModule.ts
@NgModule({
imports: [
CommonModule,
HomeRoutingModule
],
declarations: [
HomeComponent,
FirstComponent,
SecondComponent
]
})
export class HomeModule { }
home.routing.module.ts
const routes: Routes = [
{
path: "",
component: HomeComponent,
children: [{
path: 'first',
component: FirstComponent
},{
path: 'second',
component: SecondComponent
}]
}
];
@NgModule({
exports: [RouterModule],
imports: [RouterModule.forChild(routes)]
})
export class HomeRoutingModule{ }
home.component.ts
@Component({
template: '<select (change)="selectedComponent($event.target.value)">
<option value="First">First</option>
<option value="Second">Second</option>
</select>'
})
export class HomeComponent {
private selectedComponent(selectedValue: string): void {
if (selectedValue === "First")
this.router.navigate(['/home/first']);
else
this.router.navigate(['/home/second']);
}
}
You should inject the ActivatedRoute or RouterState object to get the active route and select the good option in your select.