如何重置选择默认值Angular2

Ama*_*noy 8 angular

我有一个选择第一个选项作为硬编码只是为了显示占位符和对象列表,点击清除我需要重置选择到第一个选项,我不能在这里做,有没有办法??

<select class="form-control" aria-placeholder="Select File" style=" margin-right:5px;padding:0px;width:400px" [(ngModel)]="ddlFileId" (change)="loadFiles($event.target.value)"  [ngModelOptions]="{standalone: true}" >
    <option [value]="''" disabled selected>Select File</option> // this will appear like a place holder
    <option *ngFor="let file of AllFileIDS" [value]="file.FileID" [ngValue]="file.FileID">{{file.FileID}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我试过了

  this.ddlFileId = "";
Run Code Online (Sandbox Code Playgroud)

我的尝试

  • 使数据源为空并重新分配
  • 给了一个值,而不是""[(ngmodel)]
  • 我甚至添加了一个标志,并尝试将其分配给[选定]它仍然无法正常工作

有什么方法除了使这个字典成为一个字典并添加第一个对象与设置禁用属性作为它的标志?,这就是我现在正在计划的.

其他SO问题对我没有帮助

cma*_*tin 3

我不太确定你是如何重置你的表单的,但我也一直在努力将选择重置回 Angular 2 中的默认值。不过,我已经让它可以与一些自定义值设置一起使用。在我的场景中,我使用 0 作为我的选择的默认值,但我尝试了 '' 并且它也有效。我用下面的空字符串默认值替换了我的 0 默认值。请注意,我没有使用绑定 [value],而只是使用常规值和单引号,而不是像您那样使用双引号。

<select id="selectSchool" [disabled]="user.roleId>2" class="form-control" [(ngModel)]="model.schoolId" name="schoolid" required (ngModelChange)="onSchoolChange($event)">
    <!--<option value="0" selected>Select School</option>-->
    <option value='' disabled selected>Select File</option>
    <option value="{{school.id}}" *ngFor="let school of schools">{{school.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我使用 ViewChild 将表单拉入我的 component.ts 文件:

import { ViewChild, Component, OnInit } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

将表单设置为组件中的变量:

export class UserComponent {
    @ViewChild("f")
    f: NgForm;
Run Code Online (Sandbox Code Playgroud)

我的 HTML 模板中的表单标记如下所示:

<form name="form" class="form-horizontal" (ngSubmit)="f.form.valid && submit()" #f="ngForm" novalidate>
Run Code Online (Sandbox Code Playgroud)

我的提交功能在提交后清除表单

submit(): void {
    // my submit code....

    // reset form
    this.f.resetForm();

    // After the reset, the selects will be cleared to nulls
    // even setting the model values back to '' or 0 does not rebind them. (seems like a bug)
    // but setting the form values back manually works.
    this.f.form.controls.schoolid.setValue('');  // <--- Here is resetting a select back to a default '' value
    this.f.form.controls.active.setValue(true);
    this.f.form.controls.roleid.setValue(0);  // <-- Here is resetting a select back to a default 0 value
    this.f.form.controls.radioGender.setValue("M");
}
Run Code Online (Sandbox Code Playgroud)