Adding formControlName makes the default value disappear in my form's dropdown in Angular

被刻印的时光 ゝ 提交于 2019-12-24 10:48:45

问题


I have this select element and I'm seeing something odd, when I add the formControlName to the tag the initial value "month" doesn't display, but if I remove it, it displays but doesn't validate correctly because it can't bind.

Here is my form and the html

this.registerForm = this.fb.group({
  gender: ['male'],
  email: ['', [Validators.required, Validators.email]],
  username: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],

  month: ['', Validators.required],
  day: ['', Validators.required],
  year: ['', Validators.required],
  city: ['', Validators.required],
  country: ['', Validators.required],
  password: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(10)]],
  confirmPassword: ['', Validators.required]
}, {
  validator: this.passwordMatchValidator
});
<div class="form-group col-4 col-sm-4 col-md-4">
  <select [ngClass]="{'is-invalid': registerForm.get('month').errors && registerForm.get('month').dirty}" class="form-control" id="inputState1" formControlName="month">
    <option disabled hidden selected>Month</option>
    <option>Jan</option>
    <option>Feb</option>
    <option>Mar</option>
    <option>Apr</option>
    <option>May</option>
    <option>Jun</option>
    <option>Jul</option>
    <option>Aug</option>
    <option>Sep</option>
    <option>Oct</option>
    <option>Nov</option>
    <option>Dec</option>
  </select>
  <div class="invalid-feedback" *ngIf="registerForm.get('month').dirty && registerForm.get('month').hasError('required')">Month required</div>
</div>

and here is what I see

formControlName="month"

and now when I remove

formControlName="month"

I see this


回答1:


Please add the value attributes to the option elements.

<form [formGroup]="registerForm">
  <div>
  <input formControlName="email">
  </div>
  <div>
  <select class="form-control" formControlName="month">
      <option value="" hidden selected>Select a month</option>
      <option value="1">Jan</option>
      <option value="2">Feb</option>
  </select>
  </div>
  </form>

Working code here: https://angular-reactive-form-dropdown.stackblitz.io



来源:https://stackoverflow.com/questions/57023625/adding-formcontrolname-makes-the-default-value-disappear-in-my-forms-dropdown-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!