|
| 1 | +import {AsyncPipe} from '@angular/common'; |
| 2 | +import {Component, signal} from '@angular/core'; |
| 3 | +import {FormControl, ReactiveFormsModule} from '@angular/forms'; |
| 4 | +import {MatAutocompleteModule} from '@angular/material/autocomplete'; |
| 5 | +import {MatFormFieldModule} from '@angular/material/form-field'; |
| 6 | +import {MatInputModule} from '@angular/material/input'; |
| 7 | +import {Observable, of} from 'rxjs'; |
| 8 | +import {delay, finalize, startWith, switchMap} from 'rxjs/operators'; |
| 9 | + |
| 10 | +/** @title Autocomplete with asynchronous loading */ |
| 11 | +@Component({ |
| 12 | + selector: 'autocomplete-loading-example', |
| 13 | + templateUrl: 'autocomplete-loading-example.html', |
| 14 | + styleUrl: 'autocomplete-loading-example.css', |
| 15 | + imports: [ |
| 16 | + MatFormFieldModule, |
| 17 | + MatInputModule, |
| 18 | + MatAutocompleteModule, |
| 19 | + ReactiveFormsModule, |
| 20 | + AsyncPipe, |
| 21 | + ], |
| 22 | +}) |
| 23 | +export class AutocompleteLoadingExample { |
| 24 | + myControl = new FormControl(''); |
| 25 | + options = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California']; |
| 26 | + filteredOptions: Observable<string[]>; |
| 27 | + isLoading = signal(true); |
| 28 | + |
| 29 | + constructor() { |
| 30 | + this.filteredOptions = this.myControl.valueChanges.pipe( |
| 31 | + startWith(''), |
| 32 | + switchMap(value => { |
| 33 | + this.isLoading.set(true); |
| 34 | + return this._filter(value || '').pipe(finalize(() => this.isLoading.set(false))); |
| 35 | + }), |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + private _filter(value: string): Observable<string[]> { |
| 40 | + const filterValue = value.toLowerCase(); |
| 41 | + const results = this.options.filter(option => option.toLowerCase().includes(filterValue)); |
| 42 | + |
| 43 | + // Simulate an asynchronous request. |
| 44 | + return of(results).pipe(delay(500)); |
| 45 | + } |
| 46 | +} |
0 commit comments