设置默认 select 列表值 Angular2

Set default select list value Angular2

我想将 angular 2 中 select 的默认选项设置为 "Select an option"。这是我到目前为止的代码:

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>

如何将其启用为默认选项?它与我使用 ngModel

的数组是分开的

您应该给该选项一个值,将 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>

如果您想在开始时选择此选项 - 通常是在 ngModel 的值为 undefined 时,您只需告诉 Angular 此选项是负责 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

如果您使用 [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
}