我正在尝试使用从JSON读取的值实现正常的自动完成,然后在下拉列表中显示以选择其中之一,然后使用常规的注册按钮将其推送到服务器。问题是,无论我做什么,总是总是被“”而不是值所推动。
我的component.html看起来像这样:
<mat-form-field class="example-full-width">
<input matInput placeholder="Country" aria-label="Country" [matAutocomplete]="auto" [formControl]="country">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let country of filteredCountries | async" name="country" [value]="country.name">{{country.name}}</mat-option>
</mat-autocomplete>
<mat-error *ngIf="formErrors.country" class="form__error">{{ formErrors.country }} </mat-error>
</mat-form-field>
要过滤内容,我做了有角示例“自动完成概述”所示的操作:https://material.angular.io/components/autocomplete/examples
过一会儿,过滤器就可以正常工作了,一切都显示出来了。
component.ts的signUp()方法如下所示:
public signUp() {
this.FormService.markFormGroupTouched(this.registerForm);
console.log(this.registerForm.get("username").value, this.registerForm.get("password").value, this.registerForm.get("email").value, this.registerForm.get("firstname").value, this.registerForm.get("lastname").value, this.registerForm.get("country").value, this.registerForm.get("dateOfBirth").value, this.registerForm.get("gender").value)
if (this.registerForm.valid) {
this.registrationService.register(this.registerForm.get("username").value, this.registerForm.get("password").value, this.registerForm.get("email").value, this.registerForm.get("firstname").value, this.registerForm.get("lastname").value, this.registerForm.get("country").value, this.registerForm.get("dateOfBirth").value, this.registerForm.get("gender").value).subscribe(response => console.log(response));
this.snackbar.open('Succesfully submitted a valid form. yay!', 'Close', {
duration: 5000,
});
this.registerForm.reset();
this.router.navigate(['login']);
} else {
//console.log(this.formErrors)
this.formErrors = this.FormService.validateForm(this.registerForm, this.formErrors, false)
}
}
当然,该表格无效,因为国家/地区的值始终为“”。我已经预料到的一个问题是,我将FormGroup与Validation一起使用,并且要使autoComplete正常工作,我需要使用新的FormControl创建过滤器。
开始时,我的代码看起来有所不同。我曾经打电话给[formControl]="countryCtrl"
,但这引起了问题,因此我将其重命名为我现有的"control"
。
也许还有必要是我的FormGroup:
public buildForm() {
this.registerForm = this.form.group({
firstname: ['', [Validators.required, Validators.minLength(4), CustomValidators.validateCharacters]],
lastname: ['', [Validators.required, CustomValidators.validateCharacters]],
username: ['', [Validators.required, Validators.minLength(4), CustomValidators.validateCharacters]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required]],
passwordConfirmation: ['', [Validators.required, compareValidator('password')]],
country: ['', [Validators.required]],
dateOfBirth: ['', [Validators.required]],
gender: ['', [Validators.required]],
});
this.registerForm.valueChanges.subscribe((data) => {
this.formErrors = this.FormService.validateForm(this.registerForm, this.formErrors, true)
});
}