将选择字段占位符保留在form.reset()中,角度为6

时间:2019-07-09 10:08:21

标签: javascript angular angular-forms

This链接帮助我在选择框中使用了占位符。 所以我的代码是

<form (ngSubmit)="onSubmit(form)" #form="ngForm" class="form-sample form-position">

<div class="form-group row">
  <label class="col-sm-3 col-form-label">Membership</label>
  <div class="col-sm-9">
    <select name="membership" [(ngModel)]="membership" class="form-control" required>
      <option [ngValue]="undefined" disabled selected hidden> Please select one option </option>

      <option>Free</option>
      <option>Professional</option>
    </select>
  </div>
</div>

 <div class="form-group row">
      <label class="col-sm-3 col-form-label">State</label>
      <div class="col-sm-9">
        <select [(ngModel)]="state" class="form-control" name="state" required=""
          placeholder="Select">
          <option [ngValue]="undefined" disabled selected hidden> Please select one option </option>
          <option *ngFor="let item of statesList">{{item}}</option>
        </select>
      </div>
    </div>

  <div class="text-center container-fluid form-group">
     <button [disabled]="!form.valid" type="submit" class="btn btn-primary btn-fw text-center">Submit</button>
     <button type="button" class="btn btn-secondary btn-fw" (click)="form.reset()">Clear</button>
  </div>
</form>

这只是我代码的一小部分。上面的代码运行正常。当页面加载到选择字段Membership时,默认选项Please select one option被选中。

但是问题是当我重置表单Please select one option时,文本也会被清除。但是我希望此默认选项在表单重置后仍保持选中状态。重置我使用的form.reset()表单。

3 个答案:

答案 0 :(得分:1)

form.reset()为基础模型设置null值。由于您将undefined分配为默认选项的值,因此它们不匹配。要么提供清除表单的自定义逻辑,然后在重置时将模型值设置为undefined

<button type="button" class="btn btn-secondary btn-fw" (click)="clearForm()">Clear</button>

和您的component.ts

clearForm() {
  this.membership = undefined;
  this.state = undefined;
}

OR

将您的选项值和相应模型的初始值更改为null

<option [ngValue]="null" disabled selected hidden> Please select one option </option>

和您的component.ts

membership = null;
state = null;

这是第二个https://stackblitz.com/edit/angular-ngvh9p

的演示

答案 1 :(得分:0)

如果您更改了选择中的值,则需要在重置表单时将membership的值设置为undefined。我不知道form.reset()的作用,但可能会将值设置为null

答案 2 :(得分:0)

我有一个类似的问题。

在新标签页中打开页面,在初始加载时显示占位符/默认值,然后离开页面并返回,该页面为空白。

我必须添加[ngValue = "null"]并将模型中的值最初设置为'null'

此后才出现。

Buggy代码:

<select name="title" [(ngModel)]="model.title">
    <option selected disabled> PLACEHOLDER </option>
    <option *ngFor="let title of titles" [value]="title"> title </option>
</select>

在component.ts中,初始值设置为model.title = '',即“未定义”。

修复代码是通过添加显式ngValue并将其设置为'null':

<select name="title" [(ngModel)]="model.title">
    <option [ngValue]="null" selected disabled> PLACEHOLDER </option>
    <option *ngFor="let title of titles" [value]="title"> title </option>
</select>

,还设置model.title = null的初始值。