Angular - 如何根据Dropdown选项显示输入

时间:2017-09-06 11:29:37

标签: html angular

我希望在"其他"选项在下拉列表中选择,但无法弄清楚如何 -

这是我的代码

   <div class="form-group">
      <label for="college">College:</label>
      <select class="form-control" id="college" ngModel name="college_name" required>
        <option>Ajay Kumar Garg Engineering College</option>
        <option>Others- Please Specify Below</option>
      </select>
    </div>
    <div class="form-group" *ngIf="showfield">
      <label for="name">Enter College Name:</label>
      <input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
    </div>

showfield = false;在.ts文件中设置

3 个答案:

答案 0 :(得分:5)

在你的组件中取一个变量,

<强> selectedValue: string = '';

只需将selectedvalue分配给ngModel,然后使用该值显示文字字段。

此外,选项需要value attribute,并且需要存储在ngModel

中的值
<div class="form-group">
      <label for="college">College:</label>
      <select class="form-control" id="college" [(ngModel)]="selectedValue" name="college_name" required>
        <option value="college">Ajay Kumar Garg Engineering College</option>
        <option value="others">Others- Please Specify Below</option>
      </select>
 </div>
    <div class="form-group" *ngIf="selectedValue == 'others'">
      <label for="name">Enter College Name:</label>
      <input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
    </div>

答案 1 :(得分:2)

你可以这样做

   <div class="form-group">
      <label for="college">College:</label>
      <select class="form-control" id="college" [(ngModel)]="collegeName" name="college_name" required>
        <option value="AKGEC">Ajay Kumar Garg Engineering College</option>
        <option value="other">Others- Please Specify Below</option>
      </select>
    </div>
    <div class="form-group" *ngIf="collegeName === 'other'">
      <label for="name">Enter College Name:</label>
      <input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
    </div>

答案 2 :(得分:0)

您的选项必须具有与之关联的值,所选选项值将设置为与您的下拉列表选择相关联的模型。您可以按如下方式检查show / hide:

<div class="form-group">
          <label for="college">College:</label>
          <select class="form-control" id="college" [(ngModel)]="selectedVal" name="college_name" required>
            <option value="ajay">Ajay Kumar Garg Engineering College</option>
            <option value="others">Others- Please Specify Below</option>
          </select>
        </div>
        <div class="form-group" *ngIf="selectedVal==='others'">
          <label for="name">Enter College Name:</label>
          <input type="text" class="form-control" id="name" ngModel name="other_college_name" required>
</div>