将下拉列表的选定ID绑定到输入并将其视为默认值

时间:2019-02-10 17:39:53

标签: angular angular-ngmodel angular-ng

我已经编写了一个CRUD应用程序,可以使用ngForm将数据插入Firebase。在这种形式下,我添加了一个下拉列表和一个输入,当下拉值更改时,输入(选择选项的ID)也随之更改,在这里我添加了我的标记代码:

<div class="form-group">
          <label>Visit Reason</label>
          <select class="form-control" name="Reason" #Reason="ngModel" [(ngModel)]="patientService.selectedPatient.Reason" (change)="onSelect($event.target.value)">
            <option disabled value=''>-- Select One --</option>
            <option *ngFor="let r of reasons" [value]="r.id">{{r.name}}</option>
          </select>
        </div>
<div class="form-group">
          <input id="txtPrice" readonly="true" style="text-align:left" name="Price" #price="ngModel" [(ngModel)]="patientService.selectedPatient.Price" value="{{selectedReason.id | number:'.0'}}" class="form-control" placeholder="Price" autocomplete="Off">
        </div>

这是我的组件代码:

class Reason {
  id: number;
  name: string;
}

public reasons: Reason[] = [
    { id: 60, name: "DC Visit" },
    { id: 350, name: "Inject - 1" },
    { id: 700, name: "Inject - 2" },
    { id: 500, name: "Inject - 3" },
    { id: 1000, name: "Inject - 4" }
  ];

  public selectedReason: Reason = this.reasons[''];
  onSelect(reasonId) { 
      this.selectedReason = null;
      for (var i = 0; i < this.reasons.length; i++)
      {
        if (this.reasons[i].id == reasonId) {
          this.selectedReason = this.reasons[i];
        }
      }
  }

我想将默认的输入值添加到数据库中,但是我认为必须考虑(ngmodelchange),我不知道如何。尝试了不同的方法,但没有用。

谢谢。...

1 个答案:

答案 0 :(得分:0)

尝试一下:

import { Component } from '@angular/core';

class Reason {
  id?: number;
  name?: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public reasons: Reason[] = [
    { id: 60, name: "DC Visit" },
    { id: 350, name: "Inject - 1" },
    { id: 700, name: "Inject - 2" },
    { id: 500, name: "Inject - 3" },
    { id: 1000, name: "Inject - 4" }
  ];

  public selectedReason: Reason = {};
  public selectedPatient = {};

  onSelect(reasonId) {
    this.selectedPatient.Price = reasonId;
  }

  onSubmit() {
    console.log(this.selectedPatient);
  }

}

对于模板:

<form>
  <div class="form-group">
    <label>Visit Reason</label>
    <select class="form-control" name="Reason" [(ngModel)]="selectedPatient.Reason" (change)="onSelect($event.target.value)">
      <option disabled value='null'>-- Select One --</option>
      <option *ngFor="let r of reasons" [value]="r.id">{{r.name}}</option>
    </select>
  </div>

  <div class="form-group">
    <input id="txtPrice" readonly="true" name="Price" [(ngModel)]="selectedPatient.Price" class="form-control" placeholder="Price" autocomplete="Off">
  </div>

  <button type="button" (click)="onSubmit()">Submit</button>

</form>

  

这是您推荐的Working Sample StackBlitz