Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 280
Petes Avatar asked May 21 '16 22:05

Petes


People also ask

What does routerLink do in Angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.

Can I use routerLink on button?

Using Router linksAfter Angular v4 we can directly add a routerLink attribute on the anchor tag or button. Consider the following template, where routerLink attribute added to the anchor tag. The routerLink directive on the anchor tags give the router control over those elements.


2 Answers

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;
}
like image 116
Pat M Avatar answered Sep 25 '22 19:09

Pat M


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;
  }
like image 40
Morteza Manavi Avatar answered Sep 24 '22 19:09

Morteza Manavi