如何从* ngFor访问元素(对象)到我的(点击)事件?

时间:2018-01-30 05:58:47

标签: angular angular4-forms

我需要使用* ngFor访问来自modalContent(来自API的对象数组)的医生#(这是一个对象),这是一个'选项'标签。 我试图找到一种通过这种医生的方法。到我的addDoctor()'功能。这该怎么做??以下是代码

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

3 个答案:

答案 0 :(得分:0)

使用 [(ngModel)] 获取所选值

<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

答案 1 :(得分:0)

您可以对[(ngModel)]元素使用select,并在代码中使用该元素,如下所示

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

您应该声明变量selectedDoctor并在方法中使用

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

LIVE DEMO

答案 2 :(得分:0)

你可以这样喜欢

<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