How to validade an input with Angular Autocomplete

Discussão em 'Angular' iniciado por Maurício, Agosto 20, 2025.

  1. Maurício

    Maurício Guest

    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.

    Continue reading...

Compartilhe esta Página