Angular 6 Reactive Forms-如何根据对另一个输入的选择来填充一个文本字段

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

我对Angular 6和反应形式不熟悉,我试图选择一个字段以自动填充另一个字段。

目标:如果从“选择”菜单中选择数字“ 1”,则系数输入将自动填充为“ .15”。选择'2'= =“ .175”,选择“ 3”等于“ .2”。

实现此目标的最佳方法是什么?非常感谢!

这是我的表格:

<form name="form" class="form-horizontal" (ngSubmit)="createForm.form.valid && createNewMonitoringPoint()" #createForm="ngForm" novalidate>

 <select class="col-md-12 form-control" [(ngModel)]="newmp.number"
    [ngClass]="{ 'is-invalid': createForm.submitted && newmp.number.invalid }" 
    required name="number">

    <option value="" disabled selected>Choose...</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>

 </select>

 <p>Pipe Roughness Coefficient (n) </p>
 <input type="coefficient" id="coefficient" 
    #coeffcient="ngModel" name="coefficient [(ngModel)]="newmp.coefficient" 
    class="form-control" placeholder="e.g. .016" />

 <button type="submit" value="Create">Create</button>

</form>

angular typescript
1个回答
1
投票

您正在使用模板形式而不是反应形式。您只需要在选择表单上使用(change)方法即可:

<select (change)="selected()">...</select>

和逻辑:

selected() {
  if (this.newmp.number === 1) {
    this.newmp.coefficient = .15;
  } else if (this.newmp.number === 2) {
    this.newmp.coefficient = .175;
  } else if (this.newmp.number === 3) {
    this.newmp.coefficient = .2;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.