简体   繁体   中英

How to access element(object) from *ngFor into my (click) event?

I need access to 'doctor'(which is an objct) from modalContent(Array of object coming from API) using *ngFor which is on 'option' tag. I'm trying to figure out a way to pass this 'doctor' to my 'addDoctor()' function. How to do this?? Below is the code

  <div class="modal-body">
    <label for="doctor" class="lab control-label">Select Doctor</label>
    <select id="doctor" class="form-control inputlabelcommon">
      <option *ngFor="let doctor of modalContent">{{ doctor.firstName }} {{ doctor.lastName }}</option>
    </select>
  </div>
  <div class="modal-footer footer-class">
    <button class="btn btn-primary btn-class confirm-btn" (click)="addDoctor(doctor)">CONFIRM </button>
  </div>

Use [(ngModel)] to get selected value

<div class="modal-body">
    <label for="doctor" class="lab control-label">Select Doctor</label>
    <select id="doctor" [(ngModel)]="doctor"  class="form-control inputlabelcommon">
      <option *ngFor="let doctor of modalContent" [ngValue]="doctor">
        {{ doctor.firstName }} {{ doctor.lastName }}
      </option>
    </select>
  </div>
  <div class="modal-footer footer-class">
    <button class="btn btn-primary btn-class confirm-btn" (click)="addDoctor(doctor)">CONFIRM </button>
  </div>

Demo

You can use a [(ngModel)] for the select element and use that in the code as below

<div class="modal-body">
    <label for="doctor" class="lab control-label">Select Doctor</label>
    <select id="doctor" class="form-control inputlabelcommon" [(ngModel)]="selectedDoctor">
      <option [value]="doctor" *ngFor="let doctor of modalContent">{{ doctor.firstName }} {{ doctor.lastName }}</option>
    </select>
</div>
<div class="modal-footer footer-class">
    <button class="btn btn-primary btn-class confirm-btn" (click)="addDoctor()">CONFIRM </button>
</div>

You should be declaring the variable selectedDoctor and use inside the method as

addDoctor(){
   /// this.selectedDoctor          //-- can be accessed here
}

LIVE DEMO

You can so it like

<div class="modal-body">
    <label for="doctor" class="lab control-label">Select Doctor</label>
    <select id="doctor" class="form-control inputlabelcommon" #selectedDr='ngModel' ngModel name='dr'>
      <option *ngFor="let doctor of doctors;" [value]="doctor.id">{{ doctor.firstName }} {{ doctor.lastName }}</option>
    </select>
</div>

{{ selectedDr.value }}

<div class="modal-footer footer-class">
    <button class="btn btn-primary btn-class confirm-btn" (click)="addDoctor(selectedDr.value)">CONFIRM </button>
</div>

WORKING DEMO

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