Angular 2 RouterLink for Select

10,973

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

Solution 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;
}
Share:
10,973
Admin
Author by

Admin

Updated on June 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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>
    
  • M. Mariscal
    M. Mariscal over 5 years
    Really grateful, simple and it works, dont know about the good practices, but I didn't do angular and dont know anything about that but it works at once
  • Royer Adames
    Royer Adames almost 2 years
    Property 'value' does not exist on type 'EventTarget'
  • Royer Adames
    Royer Adames almost 2 years