angular - 将下拉列表的选定 ID 绑定到输入并将其视为默认值
问题描述
我已经编写了一个 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)并且我不知道如何。尝试了不同的方法,但没有一个有用。
谢谢你....
解决方案
试试这个:
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。
推荐阅读
- sql - 如何在存储过程中循环选择语句返回的每一行
- c++ - ASCII 字符串组合
- c - 在C中通过引用传递指针
- edi - EDI 标头 - 为什么 ISA12 和 GS8 都有版本号?
- r - 上传文件后如何在闪亮的应用程序中绘制图形
- kotlin - 如何在 Kotlin DSL 中设置 Rx Action Consumer
- python - 如何在熊猫数据框中创建一个布尔空列?
- java - DataFlow (Apache Beam) 中 Pub/Sub 的自定义时间戳和窗口化
- c++ - 有没有办法在 C/C++ 中撤消 SQLite3 步骤调用?
- javascript - 根据名称从条目计数中获取一行中的值