2017-01-04 122 views
5

我有一个选择第一个选项作为硬编码一个jsut显示的地方持有人和对象的清单,点击清除我需要重置选择第一个选项,我是不能这样做,有没有办法?如何重置选择默认值Angular2

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

我试图

this.ddlFileId = ""; 

我尝试

  • 取得的数据源空和重新分配它
  • 给了一个值而不是 “”,以[(ngmodel)]
  • 我甚至添加了一个标志,并试图将它分配到 [选择]它是stil不是w工作会有

难道还有比这使其成为词典并添加第一个对象为它设置为禁用的属性作为标志,以任何方式与其他的方式?,现在那是什么亚姆规划。

其他SO问题没有帮助我

+0

<选项[值] =后“‘’”意味着两个单引号为你的价值。 this.ddlFileId =“''”;应该工作然后 – zerohero

+0

它没有我试过“选择文件” –

+1

删除“禁用”,看?可以是默认的HTML行为 – zerohero

回答

2

我不清楚自己是如何重置的形式,但我已经对重新选择返回到2角的默认值,以及挣扎。然而,我已经得到它与一些自定义值的设置。在我的情况下,我使用0作为我的选择的默认值,但我尝试了'',它也可以。我用下面的空字符串默认值替换掉了我的0默认值。请注意,我没有使用绑定[值],而只是一个常规值,只有单引号,而不是双引号。

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

我拉我的形式我component.ts文件中使用ViewChild:

import { ViewChild, Component, OnInit } from '@angular/core'; 

设置窗体中的变量组成:

export class UserComponent { 
    @ViewChild("f") 
    f: NgForm; 

我的形式标记在HTML模板看起来像这样:

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

我提交函数,用于清除表单提交

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"); 
}