Angular2选择默认的第一个选项

lar*_*595 9 angular

如何在角度2中默认选择第一个选项,以下代码似乎不起作用.

<select id="sType" class="form-control" [(ngModel)]="params.searchType"> 
     <option *ngFor="let t of sTypes" [ngValue]="t.value" [attr.selected]="$index == 0 ? true : null">{{t.name}}</option> 
</select>
Run Code Online (Sandbox Code Playgroud)

Amr*_* LS 9

您可以使用索引值默认选择第一个选项.

<select id="sType" class="form-control" [(ngModel)]="params.searchType"> 
 <option   *ngFor="let t of sTypes; let i = index" [attr.value]="t.value" [attr.selected]="i == 0 ? true : null">{{t.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)


Ado*_*lfo 5

这适用于角度 4.1.3:

<option *ngFor="let t of sTypes; let i = index" [value]="t.value" [selected]="i==0">
Run Code Online (Sandbox Code Playgroud)


Vip*_*ock 2

尝试使用这个

<select id="sType" class="form-control" [(ngModel)]="params.searchType" (ngModelChange)="onChange($event)"> 
     <option *ngFor="let t of sTypes" [Value]="t.value">{{t.name}}</option> 
</select>
Run Code Online (Sandbox Code Playgroud)

在控制器/组件使用中-

this.params.searchType=sTypes[0]

onChange(updatedValue) {
this.params.searchType = updatedValue;
//other code
}
Run Code Online (Sandbox Code Playgroud)