Angular 2 RouterLink for Select

允我心安 提交于 2019-12-10 15:38:10

问题


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>

回答1:


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.

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



回答2:


Html template:

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

Component:

import {Router} from '@angular/router-deprecated'; //or updated version

constructor(private router: Router){}

navigateTo(value) {
    if (value) {
        this.router.navigate([value]);
    }
    return false;
}


来源:https://stackoverflow.com/questions/37368491/angular-2-routerlink-for-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!