Bhe*_*zie 1 html5 select angular2-ngmodel angular
我想将角度2中的选择的默认选项设置为"选择一个选项".这是我到目前为止的代码:
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>
Run Code Online (Sandbox Code Playgroud)
打字稿
changes(){
console.log(this.example.option);
}
Run Code Online (Sandbox Code Playgroud)
我的html中有一行:
<option disabled selected>Select a Custom Fix</option>
Run Code Online (Sandbox Code Playgroud)
如何启用此选项作为默认选项?它与我用于ngModel的数组分开
如果你想在开始时选择这个选项 - 通常是在ngModel值的时候undefined,你只需告诉Angular这个选项负责undefined值,所以它应该是:
<option disabled [ngValue]="undefined">Select a Custom Fix</option>
Run Code Online (Sandbox Code Playgroud)
您还需要更正[(ngModel)]绑定 - 现在您正尝试将所选值绑定到数组本身.你应该绑定到其他一些属性,例如:
<select id="example" name="example" class="form-control" [(ngModel)]="example">
Run Code Online (Sandbox Code Playgroud)
(你可以在这里看到工作解决方案:http://plnkr.co/edit/Zu29ztqaaDym1GYDAhtJ?p = preview)