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

后端 未结 3 1316
孤城傲影
孤城傲影 2021-01-28 06:41

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:

相关标签:
3条回答
  • 2021-01-28 07:13

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-28 07:17

    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;
    }
    
    }
    
    0 讨论(0)
  • 2021-01-28 07:20

    Just in your ts, inside ngOnInit

    selectedServiceType : any;
    ngOnInit() {
      //make sure you have values for **`services`**
      this.selectedServiceType = services[0];
    }
    
    0 讨论(0)
提交回复
热议问题