【问题标题】:Angular 2 RouterLink for Select用于选择的 Angular 2 RouterLink
【发布时间】:2016-05-21 22:09:25
【问题描述】:

我想在我的页面上使用选择元素创建导航。在锚标记上使用 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>

【问题讨论】:

    标签: angular angular2-routing angular2-template


    【解决方案1】:

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

    【讨论】:

    • 真的很感激,简单而且有效,不知道好的做法,但我没有做过角,对此一无所知,但它立即有效
    【解决方案2】:

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

    如果您查看 Angular 2 路由器 source codeRouterLink 指令,您会发现它也在幕后使用 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;
      }
    

    【讨论】:

      猜你喜欢
      • 2017-08-23
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2016-12-16
      • 2017-05-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多