2016-05-15 70 views
4

爲空,我有以下的標記:如何設置選擇選項值角2

<select [ngModel]="selectedCategory" 
    (ngModelChange)="selectCategory($event && $event != 'null' ? $event : null)"> 

    <option [value]="null">(all categories)</option> 
    <option *ngFor="let cat of categories" [ngValue]="cat">{{cat.name}}</option> 

</select> 

和打字稿:

export class MyComp { 
    public categories: Category[]; 
    public selectedCategory: Category; 
    public selectCategory(cat: Category) { 
     this.selectedCategory = cat; 
     doStuff(); 
    } 
} 

它只是看起來並不像正確的方式做它。有沒有其他更少的詳細方式來獲得值爲null(不是'null')的默認選項?我不能把默認選項放在categories數組中,因爲它會弄亂其他代碼。我不介意ngModelChange,因爲我需要在選擇時運行自定義代碼。這只是我想清理的$event && $event != 'null' ? $event: null部分。

我不能使用[ngValue]上的默認選項;它只是給了我一個值0: null(字符串)。並跳過設置值結果綁定selectedCategory=null不匹配默認選項,使組合框在init時未選中。

回答

2

截至目前有一個open issue in the github repository爲此。

我發現這可以用來實現你擁有的同樣的東西,但代碼稍少。它還假定您沒有使用空字符串作爲可能的值,但是如果您只是略微修改它以在條件語句中考慮這一點。

查看

<select [ngModel]="selectedCategory" 
     (ngModelChange)="selectedCategory = $event ? $event : null"> 
    <option value="">(all categories)</option> 
    <option *ngFor="let cat of categories" [ngValue]="cat">{{cat.name}}</option> 
</select> 

組件沒有額外的邏輯所需

export class MyComp { 
    public categories: Category[]; 
    public selectedCategory: Category; 
} 

如果你還是想do stuff指您的代碼示例)對模型的變化,則該方法的方法你會更適合,但如果你想要做的只是將該值設置爲有效類別或null如果沒有選擇單個類別,這會減少代碼。

+0

這將導致下拉菜單選擇空項目而不是(全部類別)項目 – rjv

3

雖然伊戈爾解決方案不是爲我工作得很對,這是我用什麼:

<select [ngModel]="selectedItem" (ngModelChange)="selectItem($event)"> 
    <option [ngValue]="null">Don't show</option> 
    <option *ngFor="let item of items" [ngValue]="item">{{item.text}}</option> 
</select> 
import { Component, Input } from '@angular/core'; 
@Component() 
export class SelectionComponent { 
    @Input() items: any[]; 
    selectedItem: any = null; 
    selectItem(item?: any) 
    { 
     // ... 
    } 
} 

還有這裏要考慮兩個重要的細節:

  1. 在模板,使您的默認選項使用null作爲ngModel,如下所示:[ngValue]="null"。這是爲了綁定一個null選項。
  2. 請務必在組件null中指定selectedItem,否則它未定義,並且您的select將顯示爲空/沒有默認選擇。