【问题标题】:Angular 6- How can I make form fields only appear if a user inputs a specific value?Angular 6-如何仅在用户输入特定值时才显示表单字段?
【发布时间】:2019-03-05 11:32:45
【问题描述】:

我有一个带有下拉列表的 Angular 表单,列表末尾是“其他”选项。如果用户选择其他,我希望出现一个新字段,允许他们输入另一个选项。

我尝试使用 ngModel,但了解到您不能将其包含在 *ngIf 语句中,但我认为我可能走在正确的轨道上。

<form  class="form-horizontal" role="form" >
       <tr>
           <td>
                <p>Location Type :</p>
           </td>
           <td> <select class="col-md-12 form-control"[(ngModel)]="newmp.locationType" name="locationType">
                   <option value="Outfall">Outfall</option>
                   <option value="Tide Gate">Tide Gate</option>
                   <option value="Upstream">Upstream Pipe</option>
                   <option value="Vault">Vault</option>
                   <option value="Other">Other</option></select>
           </td>
      </tr> 
      <tr *ngIf="locationType == Other">
           <td class="left_td">
                 <p>Other (locationType) :</p>
           </td>
           <td> 
                    <input type="text" name="locationTypeOther"  placeholder="Other (Location Type) "class="col-md-12 form-control" [(ngModel)]="newmp.locationTypeOther" />
           </td>
       </tr> 
</form>

在我的组件中我有:

newmp = {
        "locationType": "",
        "locationTypeOther": ""
        }

按照我现在的方式,“locationTypeOther”字段将在页面加载时出现,甚至在用户选择选项之前。我可能会遗漏什么?非常感谢!

【问题讨论】:

  • 抱歉,当您选择other 时应该出现什么字段?您是指第二个&lt;tr&gt; 内的&lt;input&gt; 吗?

标签: html angular forms


【解决方案1】:

而不是

<tr *ngIf="locationType == Other">

应该是

<tr *ngIf="newmp.locationType == 'Other'">

【讨论】:

  • 太好了,谢谢!看起来我需要那个模型参考。
猜你喜欢
  • 2017-01-25
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多