角度6-如何使表单字段仅在用户输入特定值时出现?

时间:2019-03-05 03:22:28

标签: html angular forms

我有一个带下拉列表的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”字段也会在页面加载时出现。我可能会丢失什么?非常感谢!

1 个答案:

答案 0 :(得分:1)

代替

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

应该是

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