Maurício
Maurício

Reputation: 25

How to validade an input with Angular Autocomplete

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.

Upvotes: 0

Views: 2131

Answers (1)

Maur&#237;cio
Maur&#237;cio

Reputation: 25

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.

Upvotes: 1

Related Questions