我是Angular的新手。
我想使用Angular 6根据下拉值浏览不同的组件。
我已经使用了路由器模块,并且从下拉列表中获取值,但是如何根据下拉列表的值导航到组件。
找到代码
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>
答案 0 :(得分:1)
routerLink
和routerLinkActive
无法与select
一起使用。将所选值绑定到元素,然后在select
上导航。完整的解决方案如下: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>
答案 1 :(得分:0)
您可以通过在组件中注入Router
服务并使用navigate
方法来实现这一点
您的HTML就是这样
<nav>
<select id="department" name="department" [(ngModel)]="department" class="form-control" (change)="navigate($event.target.value)">
<option *ngFor="let links of navLinks" [value]="links.path" [routerLink]="links.path" routerLinkActive #rla="routerLinkActive">
{{links.label}}
</option>
</select>
</nav>
您的组件应如下所示:
export class AppComponent {
navLinks = [
{ path : 'home', label : 'Home', id: 1 },
{ path : 'about', label : 'About', id: 2 }
];
name = 'Angular';
constructor(private router: Router) {
}
navigate(path) {
this.router.navigate(['/' + path])
}
}
编辑
routerLink
对您的select控件不起作用,因为select没有由RouterLink捕获的click事件
// ** Code below is copied from Angular source code on GitHub. **
@HostListener("click")
onClick(): boolean {
// If no target, or if target is _self, prevent default browser behavior
if (!isString(this.target) || this.target == '_self') {
this._router.navigate(this._commands, this._routeSegment);
return false;
}
return true;
}
有关路由here
的更多信息