How to set first option as selected where options

2019-03-04 14:37发布

问题:

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

}