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>
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.
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.
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With