I need some help.
I'm using Angular Material.
My issue is about the mat-error show/off when using autocomplete.
In my code, I have a form with an autocomplete input. The input calls a JSON object as a response.
{ name: 'Paul', id: 1 }
At this point a need to show [name], when selected on the select option, in the input. And set the option value to [id].
No problem, I've done with.
[displayWith]="displayFn"
That's ok, everything works as should, but I don't know how to validate the [id] as a number. Every time I've tried it just validate the input [name] as a string.
Why I need that? So, I will use just the [id] to build the form object [ownerId].
<input id="ownerId" type="text" matInput formControlName="ownerId" [matAutocomplete]="auto" placeholder="Digite para pesquisar..." name="doNotAutocomplete" autocomplete="doNotAutoComplete" required> <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn"> <mat-option *ngFor="let option of owners" [value]="option"> {{option.name}} </mat-option> </mat-autocomplete> <mat-error>Selecione ou cadastre um novo proprietário.</mat-error>
// Set display owner name on input form - id on value displayFn(owner: Owner): any { return owner && owner.name ? owner.name : ''; }
// Horizontal Stepper form steps this.formGroup = this.formBuilder.group({ formArray: this.formBuilder.array([ this.formBuilder.group({ ownerId: ['', [Validators.required], code: ['', Validators.required], agent: ['', Validators.required] }),
The mat-error is setting the input INVALID when the name is selected from the input.
Many thanks for any help.
My Solution,
Here in Stackoverflow, I have found a solution approach: Angular Material: How to validate Autocomplete against suggested options?
What was needed is simple, I had to create and custom validator function such as:
function ownerIdValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
if (typeof control.value === 'string') {
return { 'invalidAutocompleteObject': { value: control.value } };
}
return null; /* valid option selected */
};
}
And added here:
this.formGroup = this.formBuilder.group({
formArray: this.formBuilder.array([
this.formBuilder.group({
ownerId: ['', [Validators.required, ownerIdValidator()]],
I hope it could help someone else.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.