Search code examples
angularangular2-routingangular2-template

Angular 2 RouterLink for 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>

Solution

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