#angular #validation #rxjs #angular-material #autocomplete
Вопрос:
Я пытаюсь добавить валидатор в поле с автозаполнением, которое ведет себя асинхронно.
Я добавил метод проверки, и я вижу, что он вызывается при изменениях, но по какой-то причине он не будет устанавливать ошибки в myInput formcontrol.
Любая помощь будет признательна. Вот фрагмент соответствующего кода:
lt;mat-form-field appearance="outline" floatLabel="always"gt; lt;input type="text" matInput [formControl]="myInput" [matAutocomplete]="auto"gt; lt;button *ngIf="myInput.value" mat-button (click)="myInput.setValue('')"gt; lt;mat-icongt;closelt;/mat-icongt; lt;/buttongt; lt;mat-autocomplete #auto="matAutocomplete" [displayWith]="carToText"gt; lt;mat-option *ngFor="let car of filteredCars | async" [value]="car"gt; lt;span [innerHTML]="carToText(car) | highlight: toHighlight"gt;lt;/spangt; lt;/mat-optiongt; lt;/mat-autocompletegt; lt;mat-error *ngIf="myInput.hasError('matched-value')"gt; {{ t("error!") }} lt;/mat-errorgt; lt;/mat-form-fieldgt;
public async ngOnInit(): Promiselt;voidgt; { this.filteredCars = this.myInput.valueChanges.pipe( mergeMap((value) =gt; from(this.myInputValueChange(value))) ); ... this.myInput.setAsyncValidators(this.matchValidator()); this.myInput.updateValueAndValidity(); } private async myInputValueChange( value: Car | string): Promiselt;Car[]gt; { if (value instanceof Car) { this.onChange.emit(value); return [value]; } if (value === undefined) { return []; } this.onChange.emit(undefined); ... const results = await this.CarRepository.search(value, typeFilter); this.toHighlight = value; return results.splice(0, M_COUNT); } public matchValidator(): AsyncValidatorFn { return (control: AbstractControl): Observablelt;ValidationErrors | nullgt; =gt; this.filteredCars.pipe( map((res) =gt; { const isValid = res.length gt; 0; const returnVal = !isValid ? {"matched-value": true} : undefined; return returnVal; } ) ); }
Комментарии:
1. Можете ли вы предоставить код, в котором вы объявили свой formcontrol ?