简体   繁体   English

Angular 2 - 如何显示多选下拉菜单的选定选项?

[英]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?那么,如何在按钮单击事件中获取多个选定的值(例如 2018、2017、2016 等)?

Method 1.方法一。

In this case, you should use ngModel .在这种情况下,您应该使用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普拉克代码 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Select 2 Multi Select 在选择选项后从下拉列表中删除选项 - Select 2 Multi Select remove option from the dropdown after selected the option Angular - 默认情况下选择的选择下拉列表中的标记选项 - Angular - Mark option in select dropdown as selected by default 如果选择了另一个选择下拉列表中的一个选项,如何显示选择下拉列表 - How do I display a select dropdown list when one option on another select dropdown is selected 在 select 上显示所选选项,并带有不同的文本 Angular - Display the selected option on a select with a different text Angular 如何使已选择的选项不在另一个 select 选项下拉 JAVASCRIPT/ANGULARJs 中显示 - How to make already selected option not display in another select option dropdown JAVASCRIPT/ANGULARJs 使用多下拉菜单时获取反应选择选项 - Get react-select selected option when using multi dropdown 获取多下拉列表的选定选项 jquery angular 不起作用 - get selected option of multi dropdown jquery angular dosn't work 如何显示下拉列表中的选定选项 - How to display selected option from dropdown list 如何从下拉菜单中选择选项 - How to multi-select option from dropdown 如何使用AngularJS检查在多选下拉列表中选择了哪个选项? - How to check which option is selected in multi-select dropdown using AngularJS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM