简体   繁体   中英

How to pass Id to my API request from a selected dropdown in Angular 6?

I am using Angular 6 here i am having one dropdown which is coming from API response.

<select 
  class="form-control" 
  name="empName" 
  [(ngModel)]="allData.secondEmp" 
  (change)="typeChange()" 
  (blur)="getid($event)" 
  required
>                           
  <option 
    *ngFor="let employee of Employees" 
    value="{{employee.secondEmp}}">{{employee.firstName}}</option>
</select>

Here i am having array like

employees = [{id: 1, firstEMp: 'kaushik', secondEmp: 'krishna'}....]

Here i want to get id in my request when i change the dropdown function.

I know we need to change the value="{{employee.id}}" but i am having some other *ngIf conditions here so i cant change value here. Any other solution for this? TIA

[ngValue] = "{secondEmployee: employee.secondEmp , id: employee.id }"

尝试这个

In your Template file: use data attribute

 <select 
  class="form-control" 
  name="empName" 
  [(ngModel)]="allData.secondEmp" 
  (change)="typeChange()" 
  (blur)="getid($event)" 
  required>                           
  <option 
    *ngFor="let employee of Employees" 
    value="{{employee.secondEmp}}"
    [attr.data-empid] = "employee.id">{{employee.firstName}}</option>
</select>

In TS file: get your id

getid(e) {
    const targetIndex = e.target;
    const res = targetIndex.options[targetIndex.selectedIndex].dataset.empid;
    console.log(res);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM