角度2+强制在下拉列表中选择第一个项目

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

以下代码正在执行它应该执行的操作:

<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>

你能帮我吗?

谢谢。

angular select option
2个回答
1
投票

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

public fileName: string = 'run';

1
投票

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

TS文件

fileName: string = 'run';
© www.soinside.com 2019 - 2024. All rights reserved.