Angular 2 应用程序出现问题并在 Internet Explorer 中选择选项

and*_*eas 5 internet-explorer html-select typescript internet-explorer-11 angular

我在 Internet Explorer 中遇到了一个奇怪的问题,我希望有人能够在这里向我解释这个问题。

在我的 Angular 2 应用程序中,我有一个带有选择框的表单。用户可以在不同的模板(名称)之间进行选择。该templates属性是一个数组,在 TypeScript 组件文件中定义,并填充可能的模板名称。

html 模板如下所示:

<select required [(ngModel)]="template">
    <option *ngFor="let t of templates" [ngValue]="t">{{ t }}</option>
</select>

<button type="button" [disabled]="!form1.valid" (click)="nextForm()">Next</button>
Run Code Online (Sandbox Code Playgroud)

整个事情按预期工作(Chrome、Firefox),除非我使用 Internet Explorer 11(可能更早)。由于某种奇怪的原因,如果只有一个可用选项,我无法选择该选项。如果有两个选项,它就会按预期工作。

在 Internet Explorer 中会发生以下情况:

  • gui 渲染,最初templates只是定义为空数组
  • 我的 TypeScript 组件中的方法从我的 Restful API 获取模板名称,并将结果作为数组写入templates
  • GUI 按预期呈现选项
  • 如果只有一个选项,看起来它已被选中,但实际上并未被选中。如果我尝试使用下拉菜单并手动选择它,它仍然没有“真正”选择

template我可以通过检查绑定模型值(保持为空)来证明该选项未正确选择,并且还form1.valid显示falseform1是整个表单的名称,请注意,选择标签是必需的)。

到目前为止我发现的 IE 的唯一解决方法就是定义

if (this.templates.length > 0) this.template = this.templates[0]
Run Code Online (Sandbox Code Playgroud)

在我成功创建模板数组之后。但如果你问我,这应该是没有必要的。

为什么 IE 会这样,有没有更好的方法来解决这个问题?


编辑:它不必对动态选项或 *ngFor 执行任何操作。我尝试了一个只有一个选项的静态示例,但无法在 IE 11 中选择它:

<select required [(ngModel)]="template">
    <option>Test</option>
</select>
Run Code Online (Sandbox Code Playgroud)

Tar*_*haf 1

虽然我无法使用静态选项重现您的问题,但如果异步加载动态选项,我们也会遇到同样的问题,请参阅此Plunker

这个原因可能是这个未解决的Angular 问题。不过,还有一种解决方法可能会有所帮助:

<form #editForm="ngForm">
    <select name="select">
        <option *ngIf="!editForm.value.select" [ngValue]="null" selected></option>
        <option *ngFor="let option of options" [ngValue]="option">{{option}}</option>
    </select>
</form>
Run Code Online (Sandbox Code Playgroud)