从Angular的下拉列表中获取选定的值

时间:2018-05-02 13:16:02

标签: angular

我对Angular很新,并且需要从下拉列表中读取所选值,并在路由时将所选值发送到组件。有人可以告诉我如何从列表中提取所选值吗?

以下是下拉列表的摘录:

<div class="dropdown-content">
                <a [routerLink]="['/schedulemanagement/autoStartStopVm']">Auto Start</a>
                <a href="#">Auto Shutdown</a>
                <a href="#">Auto Scale</a>
            </div>

3 个答案:

答案 0 :(得分:4)

以下是您的两个问题的解决方案:

  • 获取下拉值。
  • 通过路线发送参数

第一个问题绑定下拉列表的解决方案:

<强>组件:

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

解决您的第二个问题要将Params发送到路线:

来自组件:

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

因此,选定的功能将是,

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

来自HTML:

<a [routerLink]="[schedulemanagement/autoStartStopVm/', selectedLevel]">Person</a>

答案 1 :(得分:2)

我相信你正在使用Angular的bootstrap。不是<select> </select>。一个简单的解决方案可以点击链接。

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);    
  }

答案 2 :(得分:0)

试试这个,
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.
}