角度2+强制在下拉菜单中选择第一项

时间:2019-02-22 12:54:39

标签: angular select option

以下代码正在执行应做的事情:

<div class="form-group">
      <label for="file_name" class="col-sm-4 control-label">File names:</label>
      <select id="file_name"  class="col-sm-8" [(ngModel)]="fileName" name="file_name" required>
        <option value="run">use the run name</option>
        <option value="other">custom- please specify a name below</option>
        <option value="input">use the file input name</option>
      </select>
    </div>
    <div class="form-group" *ngIf="fileName === 'other'">
      <label for="custom_name" class="col-sm-4 control-label">File name:</label>
      <input  class="col-sm-8" type="text" id="custom_name" ngModel name="other_custom_name" required>
    </div>
    <div class="form-group" *ngIf="fileName === 'run'">
      <label class="col-sm-4 control-label">Enter file name:</label>
      <label  class="col-sm-8" id="run_name">{{ this.runName }}</label>
    </div>
    <div class="form-group" *ngIf="fileName === 'input'">
      <label class="col-sm-4 control-label">File name:</label>
      <label  class="col-sm-8" id="input_name">{{ this.inputDeckName }}</label>
    </div>

如果选择第二个选项,则会显示输入:

enter image description here

但是当我启动应用程序时,没有选择任何项目:

enter image description here

我希望自动选择第一项: enter image description here

将相对选项设置为选定不起作用:

<option value="run" selected>use the run name</option>

可以帮忙吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

在控制器中定义属性fileName并将其设置为要选择的选项的值。在这种情况下,您应该执行以下操作:

public fileName: string = 'run';

答案 1 :(得分:1)

已选择属性仅当您不使用ngModel时才有效。使用ngModel时,必须将默认值分配给该ngModel

TS文件

fileName: string = 'run';
相关问题