如何从选择获得所选的选项并指定为选择ngModel(How to get selected opti

2019-09-27 06:06发布

I have the following select menu:

<div class="medium-3 columns">
    <label>First Menu
        <select name="first-menu">
            <option *ngFor="let i of items" [value]="i.name">{{i.name}}</option>
        </select>
    </label>
</div>

I would assing a model to the select menu so i edited the code in the following way (i see it here):

<div class="medium-3 columns">
    <label>First menu
        <select [ngModel]="myForm.firstMenu" (ngModelChange)="onSelected($event)" name="first-menu">
            <option *ngFor="let i of items" [value]="i.name">{{i.name}}</option>
        </select>
    </label>
</div>

On ngModelChange it triggers the following method in the component:

onSelectedFirstMenu(e: any): void {
    myForm.firstMenu = e;
}

Since i have to add several menu, i would make code reuse so i do not want to create multiple methods like onSelectedSecondMenu, onSelectedThirdMenu and so on for every html menu. So i just want to use a different ngModel for every menu (myForm.secondMenu, myForm.thirdMenu and so on...) to get the selected option. Is it possible in Angular2?

Answer 1:

我解决,有2种方式来获得相同的行为:

第一种方法(优选的):

<div class="medium-3 columns">
    <label>First Menu
        <select [(ngModel)]="myForm.firstMenu" name="first-menu">
            <option *ngFor="let i of items" [value]="i.name">{{i.name}}</option>
        </select>
    </label>
</div>

方式二:

<div class="medium-3 columns">
    <label>First Menu
        <select [ngModel]="myForm.firstMenu" (ngModelChange)="myForm.firstMenu = $event" name="first-menu">
            <option *ngFor="let i of items" [value]="i.name">{{i.name}}</option>
        </select>
    </label>
</div>

更多信息点击这里



Answer 2:

如果我没有理解你的问题,每一个菜单都有不同的目的,因此,试图以某种方式结合的方法调用所有这些菜单的不正确。

具有用于每个那些的方法<select> s是正确的方法,它们中的每一个应当有其自己的逻辑

请让我知道如果我误解

使用[(MyForm.firstMenu)]的选择绑定到firstMenu财产



Answer 3:

像这样的东西应该根据您的具体要求:

<select [(ngModel)]="myForm.firstMenu"
constructor() {
  this.myForm.firstMenu = items[0];
}


文章来源: How to get selected option from select and assign it to select ngModel