设置默认选择列表值Angular2 [英] Set default select list value Angular2

查看:84
本文介绍了设置默认选择列表值Angular2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将角度2中的选择的默认选项设置为选择一个选项。这是我到目前为止的代码:

I want to set the default option for the select in angular 2 as "Select an option". Here is the code that I have so far:

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一起使用的数组分开

How can I enable this as the default option? It is separate from my array used with ngModel

推荐答案

如果使用 [ngValue] ,则需要将相同对象实例分配给 exampleArray 。另一个具有相同属性和值的对象实例将不会。

If you use [ngValue] then you need to assign the identical object instance to exampleArray. Another object instance with the same properties and values won't do.

如果使用 [value] = ... 而不是 [ngValue] ,则只能使用字符串,并且与包含相同字符的不同字符串实例进行字符串比较时,认为是相等的,但事实并非如此对于 exampleArray 需要引用与 [ngValue] 完全相同的对象引用的对象实例。

If you use [value]="..." instead of [ngValue], then only strings can be used and for string comparison to different string instances containing the same characters are considered equal, but that's not the case for object instances where exampleArray needs to reference the exact same object reference used with [ngValue].

实际上

[(ngModel)]="exampleArray"

在您的示例中无效,因为模型不应该是用于生成< ; option> 元素,它应该是保存所选值的属性。

in your example is invalid, because the model should not be the array that is used to generate the <option> elements, it should be a property that holds the selected value.

   <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
}

这篇关于设置默认选择列表值Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆