Angular 15 AutoComplete

Angular 15 AutoComplete

Angular 15 Material's mat-autocomplete component is a form control that provides suggestions while a user is typing in an input. It is designed to work with the Angular 15 forms module and supports both template-driven and reactive forms.

To use the mat-autocomplete component, you need to import the MatAutocompleteModule in your Angular 15 module and add it to the imports array.

Here is an example of how to use the mat-autocomplete component in a template-driven form:

<form>
  <mat-form-field>
    <input type="text" name="country" [(ngModel)]="selectedCountry" matInput [formControl]="countryControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let country of filteredCountries | async" [value]="country">

      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

In this example, we have an input element bound to the selectedCountry variable and a mat-autocomplete element with a #auto template reference variable. The mat-autocomplete element has a mat-option element for each item in the filteredCountries array, which is an observable of an array of countries that is filtered based on the value of the input.

To use the mat-autocomplete component in a reactive form, you can use the formControlName directive instead of the ngModel directive. For example:

<form [formGroup]="form">
  <mat-form-field>
    <input type="text" name="country" matInput formControlName="countryControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let country of filteredCountries | async" [value]="country">

      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

In this example, the input element is bound to the countryControl form control using the formControlName directive. The rest of the template is the same as in the template-driven form example.

There are several other options and features available for the mat-autocomplete component, such as the ability to customize the input placeholder, the no-option-found text, and the option selection behavior. You can find more information about these options in the Angular Material documentation.