Pet*_*tes 4 angular2-template angular2-routing angular
我想使用页面上的select元素创建导航.在锚标记上使用RouterLink指令很简单,但选择下拉列表是否相同?或者,当我的选择发生变化时,我是否需要在我的组件上创建自己的导航方法?
<a [routerLink]="[location]">Location</a>
<select (change)="navigate($event.target.value)">
<option>--Select Option--</option>
<option [value]="[location]">Location</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我正在寻找这样的东西:
<select>
<option>--Select Option--</option>
<option [routerLink]="[location]">Location</option>
</select>
Run Code Online (Sandbox Code Playgroud)
Html模板:
<select (change)="navigateTo($event.target.value)">
<option>--Select Option--</option>
<option value="location">Location</option>
</select>
Run Code Online (Sandbox Code Playgroud)
零件:
import {Router} from '@angular/router-deprecated'; //or updated version
constructor(private router: Router){}
navigateTo(value) {
if (value) {
this.router.navigate([value]);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
是的,您需要在组件内创建一个导航方法并将其绑定到(change)选择控件的事件,然后使用注入的Router.
如果您查看 Angular 2 Router源代码中的RouterLink指令,您会发现它也在router.navigate幕后使用来导航到目标路由。它不适用于您的select控件,因为 select 没有click由 RouterLink 指令捕获的事件,如下所示:
// ** 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7125 次 |
| 最近记录: |