簡體   English   中英

Angular 2 - 如何從select / option獲取值

[英]Angular 2 - how to get value from select / option

Angular 2的大多數選擇/選項解決方案的工作方式是返回實際內容,而不是value屬性。 但是,因為我還在學習Angular 2,所以我希望在單擊按鈕時獲得實際value屬性。 我設法在某種程度上解決了這個問題,但我不確定這是否是正確的方法。 以下是我希望它如何工作的示例:

<select #selectedCategory>
    <option *ngFor="#category of categories" [value]="category.id">{{category.name}}</option>
</select>

<button (click)="getValueFromSelect(selectedCategory.value)">

/* This returns the selected category.name, not the value attribute. */

上面的解決方案創建了以下HTML(請注意option上缺少value屬性):

<select _ngcontent-oom-3="">
  <!--template bindings={}-->
  <option _ngcontent-oom-3="">stuff 1</option>
  <option _ngcontent-oom-3="">stuff 2</option>
  <option _ngcontent-oom-3="">stuff 3</option>
</select>

下面的解決方案實際上有效,但是,我需要一個ngModel才能使它工作。

<select [(ngModel)]="selectedCategory">
    <option *ngFor="#category of categories" [value]="category.id">{{category.name}}</option>
</select>
<button (click)="getValueFromSelect(selectedCategory.value)">
/* This returns the value attribute correctly; however, do I really need a ngModel for one value? */

解決這種情況的正確方法是什么?

謝謝你的建議。

正如評論中所討論的那樣,“我希望它如何工作”的例子確實有效:

<select #selectedCategory>
   <option *ngFor="#category of categories" [value]="category.id">
     {{category.name}}
   </option>
</select>

<button (click)="getValueFromSelect(selectedCategory.value)">click me</button>

Plunker

但是,我們必須使用beta.15才能工作。 有關詳細信息,請參閱beta.15的更改日志


我更喜歡這種方法,因為它不會給組件添加屬性,也不需要使用<form>標簽(比如@Thierry的答案)。

您可以使用與ngControl指令內聯定義的ngControl

<form>
  <select #categoriesCtrl="ngForm" ngControl="categoriesCtrl">
    <option *ngFor="#category of categories" [value]="category.id">
      {{category.name}}
    </option>
  </select>
  <button (click)="getValueFromSelect(categoriesCtrl.value)">
</form>

請參閱此plunkr: https ://plnkr.co/edit/uWUS9RaGJ34PiXTJ1kPd p = preview。

你可以使用change事件調用

<form>
      <select #categoriesCtrl (change)='SelectedValue = categoriesCtrl.value'>
        <option *ngFor="#category of categories" [value]="category.id">{{category.name}}</option>
      </select>
      <button (click)="getValueFromSelect()">Get value</button>
    </form>

工作示例https://plnkr.co/edit/dQZgSyw6uc67UNhNDlZv?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM