首页 文章

Angular 2 RouterLink for Select

提问于
浏览
4

我想使用页面上的select元素创建导航 . 在锚标记上使用RouterLink指令很简单,但选择下拉列表是否相同?或者,当我的选择发生变化时,我是否需要在我的组件上创建自己的导航方法?

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

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

我正在寻找这样的东西:

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

2 回答

  • 3

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

    如果您查看Angular 2路由器source code for RouterLink 指令,您会看到它也在场景后面使用 router.navigate 导航到目标路径 . 它不适用于 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;
      }
    
  • 6

    Html模板:

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

    零件:

    import {Router} from '@angular/router-deprecated'; //or updated version
    
    constructor(private router: Router){}
    
    navigateTo(value) {
        if (value) {
            this.router.navigate([value]);
        }
        return false;
    }
    

相关问题