无法在angular2中选择中设置默认选项

时间:2017-05-01 13:27:15

标签: angular2-forms

我正在尝试在select中选择默认选项。以下是我的代码

    <select [id]="index" class="form-control" (change)="onChange($event.target.selectedIndex,$event.target.value)" (focus)="onFocus($event.target.selectedIndex)">
        <option value="" [selected]="true" disabled="true">{{'rec.select' | translate}}</option>
        <option  *ngFor="let attributeType of attributeTypeValues" [disabled]="attributeType.disabled" [value]="attributeType.attrTypeNm" 
        [selected]="attributeType.attrTypeNm===attributeEditForm.controls['attrType'].value">
            {{attributeType.attrTypeDesc}}
        </option>
    </select>

我可以看到ng-reflect-selected为true。但在UI中没有选择任何内容。

代码在首次加载时工作正常。但随着选择的更改,更改不会反映在UI中。例如,如果更改了表单值,则选择条件会更改,并且相同的选定选项不会反映在ui中。

2 个答案:

答案 0 :(得分:0)

我个人会在这种情况下使用[(ngModel)]方法:

<select [(ngModel)]="selectedValue">
  <option *ngFor="let v of values" [ngValue]="v">{{v.name}}</option>
</select>

控制器中包含以下内容:

values = [
    { id: 0, name: "Value0" },
    { id: 1, name: "Value1" },
    { id: 2, name: "Value2" },
    { id: 3, name: "Value3" },
  ];
selectedValue = this.values[0];

重要的是,默认选择需要是正确的对象实例,而不是值列表中使用的对象实例。另一个具有相同属性和值的对象实例不会做=&gt;检查对象标识。

答案 1 :(得分:0)

简单方法和最快捷的方法是检查你的* ngFor新变量是否等于[selected]中的逻辑:(示例)

<select (change)="size($event.target.value)" class="size-option" name="size">
  <option *ngFor="let number of [14, 16, 18, 20, 22]" value="{{number}}" [selected]="number == 16">{{number}}</option>
</select>
相关问题