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

ⅰ亾dé卋堺 提交于 2019-12-20 05:57:21

问题


I have worked on angular 4 project, In this project, I have a requirement to set the first option as selected where all options are created dynamically by loop. html code:

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

If anyone know about let me know. Thanks in advance!


回答1:


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



回答2:


Just in your ts, inside ngOnInit

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



回答3:


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

}


来源:https://stackoverflow.com/questions/46605259/how-to-set-first-option-as-selected-where-options-build-from-loop-in-select-box

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