我曾参与 Angular 4 项目,在这个项目中,我需要将第一个选项设置为选定的,其中所有选项都是通过循环动态创建的。 html代码:
<select [(ngModel)]="selectedServiceType" [ngModelOptions]="{standalone: true}" (ngModelChange)="getServiceType($event)">
<ng-container *ngFor="let service of services">
<option [ngValue]="service">{{service.name}}</option>
</ng-container>
</select>
如果有人知道请告诉我。提前致谢!
最佳答案
尝试这样:
<select class="form-control" (change)="onChange($event)">
<option *ngFor="let service of services; let itemIndex = index" [selected]="itemIndex == 0" [ngValue]="service.value">{{service.name}}</option>
</select>
组件.ts
export class HomeComponent implements OnInit {
private selectedServiceType: any;
private services: Array<any> = [];
constructor() {
this.services = [{
name: "Harish",
value: 5000
}, {
name: "Chandru",
value: 5001
}]
}
onChange(e) {
this.selectedServiceType = e.target.value;
}
}
关于angular - 如何将第一个选项设置为选定的选项,其中选项是从选择框 anular 4 中的循环构建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616879/