Я пытаюсь добиться нормального автозаполнения со значениями, которые считываются из моего 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 с проверкой и чтобы автозаполнение работало, мне нужно было создать фильтр с новым 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)
});
}