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

问题描述:

我对Angular还是很陌生,有一个要求,我需要从下拉列表中读取选定的值,并在路由时将选定的值发送到组件.有人可以告诉我如何从列表中提取选定的值吗?

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?

这是下拉列表的摘录:

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

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

Here is the solutions for both your questions:

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

第一个问题绑定下拉菜单的解决方案:

组件:

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

> 这里是有效的演示版

第二个问题的解决方案将Params发送到Route:

来自组件:

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>