单击Angular 7中的按钮时如何获得下拉菜单的选定选项

时间:2019-09-04 18:20:08

标签: html angular

我有一个下拉菜单,其中包含一些来自循环的选项,单击按钮后需要获取选择的选项(不是值)。我尝试使用ngModel,但是我可以获取值,而不是选项。谁能帮帮我吗?这是下面的代码

app.component.html

<div>
    <select>
        <option *ngFor="let group of groups" value="{{group.id}}">{{group.name}}</option>
    </select>
</div>
<input type="button" (click)="getVal()" value="submit"/>

app.component.ts

import { Component, ViewChild, ElementRef } from '@angular/core';

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

export class AppComponent {

    ngOnInit() {

    }

    getVal() {

    }

    groups = [{
        "id": 1,
        "name": "pencils",
        "items": "red pencil"
    },
    {
        "id": 2,
        "name": "rubbers",
        "items": "big rubber"
    },
    {
        "id": 3,
        "name": "rubbers1",
        "items": "big rubber1"
    }];
}

3 个答案:

答案 0 :(得分:1)

尝试这样:

模板:

<div>
  <select [(ngModel)]="selectedgroup">
     <option *ngFor="let group of groups">{{group.name}}</option>
  </select>
  </div>
<input type="button" (click)="getVal()" value="submit"/>

打字稿:

 selectedgroup: any

  getVal() {
    console.log(this.selectedgroup)
    console.log(this.groups.filter(x => x.name == this.selectedgroup)[0].items)
  }

请参见Stackbiltz Demo

答案 1 :(得分:0)

只需使用ngModel绑定到所选值。由于您想同时从所选选项中获取idname,因此最好获取所选的整个对象。您可以使用ngValue(来源:docs)来完成此操作。

<select [(ngModel)]="selectedGroup">
    <option *ngFor="let group of groups" [ngValue]="group">{{group.name}}</option>
</select>
selectedGroup: any;

getVal() {
    console.log(this.selectedGroup); // returns selected object
    console.log(this.selectedGroup.id); // returns selected option's id
    console.log(this.selectedGroup.name); // returns selected option's name
}

答案 2 :(得分:0)

        import { Component } from '@angular/core';
@Component({
selector: 'app-pager',
template: `
<div><select (change)="Selected($event)"><option *ngFor="let group of groups" [value]="group.name">{{group.name}}</option></select></div>
<input type="button" (click)="getVal()" value="submit"/>
<h4 [hidden]="hide">the name selected : {{ selected }} OR for click button : {{ button }} </h4>
`
})
export class PagerComponent {

selected : string = '';
button : string = '';

hide : boolean = true;
  Selected(event: any){
    //update the ui
    this.selected = event.target.value;
    this.hide=false;
  }
// or you can use the button :
getVal(){
this.button=this.selected;
}
groups=[
  {
    "name": "select your chois",
    "items": ""
  },
     {
       "name": "pencils",
       "items": "red pencil"
     },
     {
       "name": "rubbers",
       "items": "big rubber"
     },
     {
       "name": "rubbers1",
       "items": "big rubber1"
     }
  ];

}

    //you can give a value groups.name and working with $event