2016-11-16 52 views
1

我想將角度2中的選擇的默認選項設置爲「選擇一個選項」。這裏是我到目前爲止的代碼:設置默認的選擇列表值Angular2

HTML

<div class="form-group"> 
         <label class="col-md-4 control-label" for="CustomFix">Select an option:</label> 
         <div class="col-md-4"> 
          <select id="example" name="example" class="form-control" [(ngModel)]="exampleArray" (ngModelChange)="changes()"> 
           <option disabled selected>Select a Custom Fix</option> 
           <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option> 
          </select> 
         </div> 
        </div> 

打字稿

changes(){ 
console.log(this.example.option); 
} 

我在我的HTML行:

<option disabled selected>Select a Custom Fix</option> 

如何我可以啓用此作爲默認t選項?它與我的數組分開使用ngModel

+0

選項如何既殘疾人和選擇?如果它被禁用,那麼根據定義它不能被選擇。 –

回答

1

如果使用[ngValue],那麼你需要的相同對象實例分配給exampleArray 。具有相同屬性和值的另一個對象實例將不會執行。

如果使用[value]="..."代替[ngValue],那麼只有字符串可以用來和字符串比較包含相同字符的不同的字符串實例被認爲是相等的,但是這不是對對象實例的情況下exampleArray需要引用完全相同的與[ngValue]一起使用的對象引用。

實際上

[(ngModel)]="exampleArray" 
在你的例子

是無效的,因爲該模型不應該是被用於生成<option>元件陣列,它應該是保存所選擇的值的屬性。

<div class="form-group"> 
     <label class="col-md-4 control-label" for="CustomFix">Select an option:</label> 
     <div class="col-md-4"> 
      <select id="example" name="example" class="form-control" [(ngModel)]="selectedItem" (ngModelChange)="changes()"> 
       <option disabled selected>Select a Custom Fix</option> 
       <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option> 
      </select> 
     </div> 
    </div> 
constructor() { 
    this.selectedItem = exampleArray[1]; // will make the 2nd element of `exampleArray` the selected item 
} 
1

您應該給該選項一個值,將select元素綁定到ID變量,並在組件加載時設置該變量。

// controller 
 
exampleArraySelectedValue = -1;
<div class="form-group"> 
 
    <label class="col-md-4 control-label" for="CustomFix">Select an option:</label> 
 
    <div class="col-md-4"> 
 
    <select id="example" name="example" class="form-control" [(ngModel)]="exampleArraySelectedValue" (ngModelChange)="changes()"> 
 
     <option value="-1">Select a Custom Fix</option> 
 
     <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option> 
 
    </select> 
 
    </div> 
 
</div>

4

如果你想有這個選項在開始選擇 - 這通常是當ngModel的價值是undefined,你只需要告訴角度,這個選項是負責undefined值,所以它應該是:

<option disabled [ngValue]="undefined">Select a Custom Fix</option> 

你也需要做糾正你[(ngModel)]結合 - 現在你正在試圖綁定選擇價值..陣列本身。你還是結合一些其他的屬性,如:

<select id="example" name="example" class="form-control" [(ngModel)]="example"> 

(你可以看到這裏的工作解決方案:http://plnkr.co/edit/Zu29ztqaaDym1GYDAhtJ?p=preview