简体   繁体   中英

Angular 2 - How to display selected option for multi select dropdown?

<select #selectedfiscalyear multiple> 
     <option *ngFor="let fiscalyear of fiscalyears" value = {{fiscalyear.value}}> 
                {{fiscalyear.value}} 
     </option>
 </select> 
<button class="btnView">Click</button>

where

fiscalyears = [
  {
    "year": "fiscalYear",
    "value": "2018"
  },
  {
    "year": "fiscalYear",
    "value": "2017"
  },
  {
    "year": "fiscalYear",
    "value": "2016"
  },
  {
    "year": "fiscalYear",
    "value": "2015"
  },]

So, how to get the multiple selected values(such 2018,2017,2016 an so on) on button click event?

Method 1.

In this case, you should use ngModel . You won't even need the button action then.

@Component({
  selector: 'my-app',
  template: `
    <select #selectedfiscalyear multiple [(ngModel)]="selectedVal"> 
      <option *ngFor="let fiscalyear of fiscalyears"> 
           {{fiscalyear.value}} 
      </option>
    </select> 
  <h1>{{ selectedVal }}</h1>
  `
})

Plunker code


Method 2.

In case , that you really want to call that function on button click, use following code:

@Component({
  selector: 'my-app',
  template: `
    <select #selectedfiscalyear multiple [(ngModel)]="selectedVal"> 
       <option *ngFor="let fiscalyear of fiscalyears"> 
           {{fiscalyear.value}} 
       </option>
    </select> 
    <button class="btnView" (click)="selectedVal.length ? select() : null">Click</button>
    <input id="result">
  `,
})

export class App {
  constructor() {}

  select(){
    document.getElementById('result').value = this.selectedVal;
  }
}

Plunker code 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM