用于选择的 Angular 2 RouterLink [英] Angular 2 RouterLink for Select

查看:19
本文介绍了用于选择的 Angular 2 RouterLink的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用页面上的选择元素创建导航.在锚标记上使用 RouterLink 指令很简单,但是否有等效的选择下拉菜单?或者我是否需要在我的组件上创建自己的导航方法,以便在我的选择发生更改时调用?

I would like to create navigation using a select element on my page. Using the RouterLink directive on an anchor tag is simple, but is there an equivalent for a select dropdown? Or am I required to create my own navigation method on my component to be called when there is a change on my select?

<a [routerLink]="[location]">Location</a>

<select (change)="navigate($event.target.value)">
    <option>--Select Option--</option>
    <option [value]="[location]">Location</option>
</select>

我正在寻找这样的东西:

I am looking for something like this:

<select>
    <option>--Select Option--</option>
    <option [routerLink]="[location]">Location</option>
</select>

推荐答案

是的,您需要在组件内部创建导航方法并将其绑定到选择控件的 (change) 事件,然后使用注入的 Router 在该方法中进行导航.

Yes you need to create a navigation method inside your component and bind it to the (change) event of the select control and then do the navigation inside that method using an injected Router.

如果您查看 Angular 2 路由器 源代码 RouterLink 指令,你会看到它也在幕后使用 router.navigate导航到目标路线.它不适用于您的 select 控件,因为 select 没有由 RouterLink 指令捕获的 click 事件,如下所示:

If you look into the Angular 2 Router source code for RouterLink directive, you'll see that it is also using router.navigate behind the scene to navigate to the target route. It won't work for your select control since select does not have a click event which is captured by the RouterLink directive as you can see below:

// ** 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;
  }

这篇关于用于选择的 Angular 2 RouterLink的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆