2016-11-16 94 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