单击Angular 7中的按钮时如何获得下拉菜单的选定选项 [英] How to get the selected option of dropdown on click of a button in Angular 7

查看:38
本文介绍了单击Angular 7中的按钮时如何获得下拉菜单的选定选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dropdown that contains a few options coming from a loop,I need to get the selected option(not value) on click of a button. I tried with ngModel but I was able to get the value, not option. Can anyone please help me? Here is the code below

<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"
    }];
}

推荐答案

只需使用 ngModel 绑定到所选值.由于要从选定的选项中同时获取 id name ,因此最好将所选的整个对象都获取.您可以使用 ngValue (来源:文档)进行此操作

Just use ngModel to bind to the selected value. Since you want to get both id and the name from the selected option, it would be better if you get the entire object that was selected. You can do this using ngValue (Source: 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
}

这篇关于单击Angular 7中的按钮时如何获得下拉菜单的选定选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆