0

我从事 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>

如果有人知道,请告诉我。提前致谢!

4

3 回答 3

1

试试这样:

<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;
    }
}
于 2017-10-06T12:44:15.787 回答
0

添加此代码

<select (change)="onChange($event.target.value)"  value={{selectedService}}>
<ng-container>
    <option *ngFor="let service of services" >{{service.name}}</option>
</ng-container>
</select>

你 component.ts 应该是

export class YourClass implements OnInit {
  selectedService: any;
  services:any = [];


--your API call code set values to services array
this.services=this.service.APImethod()

onChange(newValue) {  
this.selectedService=newValue;
}

}
于 2018-03-27T13:30:23.253 回答
0

就在你的ts里面ngOnInit

selectedServiceType : any;
ngOnInit() {
  //make sure you have values for **`services`**
  this.selectedServiceType = services[0];
}
于 2017-10-06T12:05:08.343 回答