skip to Main Content

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


  1. 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:

    <select [formControl]="urlSelect">
        <option [value]="null" disabled>Please select</option>
        <option value="/add-product">Add a product</option>
    </select>
    
    public urlSelect = new FormControl<string | null>(null);
    
    public ngOnInit(): void {
        this.urlSelect.valueChanges.subscribe((url) => {
            if (url) {
                const urlTree: UrlTree = this.router.createUrlTree([url]);
                this.router.navigateByUrl(urlTree);
            }
        });
    }
    

    You need to import FormsModule for this to work, and you should make sure to unsubscribe from urlSelect.valueChanges when the component is destroyed.

    Login or Signup to reply.
  2. redirectToUrl(url: String) {
      if (url) this.router.navigateByUrl(url);
    } 
    

    or

    redirectToUrl(url: String) {
      if (url) 
         this.router.navigate([url]);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search