How to set first option as selected where options build from loop in select box anular 4

自作多情 提交于 2019-12-02 11:34:48

Try like this :

<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>

component.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;
    }
}

Just in your ts, inside ngOnInit

selectedServiceType : any;
ngOnInit() {
  //make sure you have values for **`services`**
  this.selectedServiceType = services[0];
}

add this code

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

and you component.ts should be

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;
}

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!