0

我已经编写了一个 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)并且我不知道如何。尝试了不同的方法,但没有一个有用。

谢谢你....

4

1 回答 1

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>

这是您参考的工作示例 StackBlitz

于 2019-02-10T18:27:45.493 回答