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