14

I am pretty new to Angular and have a requirement where I need to read the selected value from a drop-down list and send the selected value to a component while routing. Can someone tell how do I extract the selected value from the list?

Here's a snippet of the drop-down list:

<div class="dropdown-content">
                <a [routerLink]="['/schedulemanagement/autoStartStopVm']">Auto Start</a>
                <a href="#">Auto Shutdown</a>
                <a href="#">Auto Scale</a>
            </div>
Debo
  • 505
  • 4
  • 13
  • 24
  • Possible duplicate of [Angular 2: How to get the selected value from different options of a form?](https://stackoverflow.com/questions/34950160/angular-2-how-to-get-the-selected-value-from-different-options-of-a-form) – msanford May 02 '18 at 13:45

3 Answers3

28

Here is the solutions for both your questions:

  • To get dropdown value.
  • To send params through route

Solution to your first question binding dropdown:

Component:

import { Component } from '@angular/core';
import { Router } from '@angular/router';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  constructor(private route: Router){ }

  selectedLevel;
  data:Array<Object> = [
      {id: 0, name: "name1"},
      {id: 1, name: "name2"}
  ];

  selected(){
    console.log(this.selectedLevel)
  }
 }

HTML:

<h1>Drop Down</h1>
<select [(ngModel)]="selectedLevel" (change)="selected()">
    <option *ngFor="let item of data" [ngValue]="item">{{item.name}}</option>
</select>
{{selectedLevel | json}}

Here is a working DEMO


Solution to your second question To send Params to Route:

From Component:

this.route.navigate(['schedulemanagement/autoStartStopVm/' + data]);

So, selected function will be,

  selected(){
    console.log(this.selectedLevel)
   this.route.navigate(['schedulemanagement/autoStartStopVm/' + data]);
  }

From HTML:

<a [routerLink]="[schedulemanagement/autoStartStopVm/', selectedLevel]">Person</a>
Sravan
  • 18,467
  • 3
  • 30
  • 54
3

I believe you are using bootstrap with Angular. Not <select> </select>. An easy solution could be onclick of the link.

html:

<div class="dropdown-content">
                <a (click)="getSelectedDropdown('1') [routerLink]="['/schedulemanagement/autoStartStopVm']">Auto Start</a>
                <a (click)="getSelectedDropdown('2') href="#">Auto Shutdown</a>
                <a (click)="getSelectedDropdown('3') href="#">Auto Scale</a>
            </div>

component.ts:

getSelectedDropdown(link) {
        alert(link);    
  }
SK.
  • 1,390
  • 2
  • 28
  • 59
0

Try this,
HTML:

<a [routerLink]="['/schedulemanagement/autoStartStopVm']" (click)="testEvent($event)">Test Event Link</a>

TS:

testEvent(event) {
console.log(event) //check the event object and get your required values.
}
haMzox
  • 2,073
  • 1
  • 12
  • 25