绑定下拉的选择ID输入和考虑它作为默认值

问题描述 投票:0回答:1

我已经写了一个CRUD应用插入使用ngForm数据为火力点。在这种形式我添加了一个下拉列表和输入,当下拉值的变化,输入(选择选项的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),我不知道怎么办。尝试了多种不同的方法,但没有一个是有用的。

谢谢....

angular angular-ngmodel angular-ng
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>

以下是为您的参考一Working Sample StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.