How to get selected option from select and assign

2019-07-28 23:24发布

问题:

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?

回答1:

I solved and there are 2 ways to get the same behaviour:

First way (preferred):

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

Second way:

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

More info here



回答2:

If i understand your question correctly, every single menu has a different purpose, therefore, trying to somehow combine the invoked method for all of those menus is incorrect.

Having a method for each of those <select>s is the right approach, each one of them should have its' own logic

Please let me know if i misunderstood

Use [(MyForm.firstMenu)] to bind the select to your firstMenu property



回答3:

Something like this should do depending on your concrete requirements:

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