I’m trying to get my select tag to redirect me to a url that is in option
value. For example this is my code:
<select #selectElement (change)="redirectToUrl(selectElement.value)">
<option value="/add-product">Add a product</option>
</select>
And in .component.ts is:
@ViewChild('selectElement', { static: false })
selectElement!: ElementRef;
redirectToUrl(url: String) {
if (url){
const urlTree: UrlTree = this.router.createUrlTree([url]);
this.router.navigateByUrl(urlTree);
}
}
And ofc, when I select the option, nothing happens. I don’t know what I’m missing…
2
Answers
With only one option the change event will never fire, as the option is selected by default. You can add a null option as a kind of placeholder when using a formControl that is preset to
null
:You need to import FormsModule for this to work, and you should make sure to unsubscribe from
urlSelect.valueChanges
when the component is destroyed.or