I am new to Angular.
I wanted to navigate different component based on the drop down value using Angular 6.
I have used router Module and am getting the values from drop down, but how to navigate to component based on the value of the drop down.
find the code
1> app.routing.module
const routes: Routes = [
{path:'about',component : AboutComponent},
{path:'home',component : HomeComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
2> app.component.ts
export class AppComponent {
navLinks = [
{ path : 'home', label : 'Home', id: 1 },
{ path : 'about', label : 'About', id: 2 }
];
3> app.component.html
<nav>
<select id="department" name="department" [(ngModel)]="department" class="form-control">
<option *ngFor="let links of navLinks" [value]="links.id" [routerLink]="links.path" routerLinkActive #rla="routerLinkActive">
{{links.label}}
</option>
</select>
</nav>
routerLink
and routerLinkActive
won't work out of the box with select
. Bind the selected value to an element, then navigate on select
. Here's the full solution: https://stackblitz.com/edit/angular-ualqhw
app.component.ts:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
export interface INavLink {
id : number;
pathLink : string;
label : string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
selectedNavLink : INavLink;
navLinks : Array<INavLink> = [
{ pathLink : '/home', label : 'Home', id: 1 },
{ pathLink : '/about', label : 'About', id: 2 }
];
constructor(private router : Router){}
routeToLink = (event : Event) => {
this.router.navigate([this.selectedNavLink.pathLink]);
}
}
app.component.html:
<nav>
<select (change)="routeToLink()" id="department" name="department" [(ngModel)]="selectedNavLink" class="form-control">
<option *ngFor="let link of navLinks" [ngValue]="link">
{{link.label}}
</option>
</select>
</nav>