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

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

问题描述

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

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>

推荐答案

是的,您需要在组件内部创建一个导航方法并将其绑定到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指令的nofollow> 源代码 ,您会看到它还在后台使用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天全站免登陆