Angular 2的大多數選擇/選項解決方案都以我們返回實際內容的方式工作,而不是value
屬性。但是,由於我仍然在學習Angular 2,我想在點擊按鈕時獲得實際的value
屬性。我設法解決了這個問題,但我不確定這是否是正確的方法。 下面是我想它是如何工作的例子:Angular 2 - 如何從選擇/選項中獲取價值
<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? */
解決這種情況的正確方法是什麼?
謝謝您的建議。
你的「我怎麼喜歡它的工作」的例子工作:[plunker](https://plnkr.co/edit/NZc3RWgERx2t2m1HWmCb?p=preview)。它返回分配給所選選項的'value'屬性的'category.id'。我喜歡這種方法,因爲它不會將屬性添加到組件。 –
這真的很奇怪,在我的例子中,當我檢查select/option元素時,我沒有'value'屬性。我基本上覆制/粘貼你的例子 - 如果你檢查元素,在你的榨取器中,每個選項都有一個'value'屬性,而我的不是。我將使用生成的HTML更新我的原始問題。 – uglycode
您使用的是哪個版本的Angular beta?你有沒有加載其他庫? –