-1

When I enter something into input, I have to find all the options that include that substring. The problem is that the filtered values ​​are not displayed correctly.

For example, I have several words: n, new, need, snow.

  1. When I enter "n", autocomplete doesn't show anything (but should show all options).
  2. When I enter "ne", it shows n, new, need, snow (but should show new, need).
  3. When I enter "new", it shows new, need (but should show only new). As if the Search service takes the previous entered value.

My template:

<form [formGroup]="myForm">
<input [formControl]="myForm.get('myInput')" type="text" [matAutocomplete]="myAutocomplete"/>
<mat-autocomplete #myAutocomplete="matAutocomplete">
    <mat-option *ngFor="let item of autocompleteItems" [value]="item">
        {{item}}
    </mat-option>
</mat-autocomplete>
</form>

In my component:

public myForm = new FormGroup({myInput: new FormControl('', [Validators.required])});
public autocompleteItems: string[] = [];

ngOnInit() {
  this.myForm.get('myInput').valueChanges
    .pipe(
        takeUntil(this.unsubscribe),
        switchMap((inputString: string) => this.mySearchService.search(inputString)))
    .subscribe((foundStrings: string[]) => {
        this.autocompleteItems = foundStrings;
        console.log(this.autocompleteItems);
    });
}

P. S. Logs show correct array of strings:

  1. Input n - n, new, need, snow.
  2. Input ne - new, need.
  3. Input new - new.

Please tell me what I'm doing wrong.

TryBetter
  • 43
  • 5

1 Answers1

0

Pipe pairwise into your valueChanges Observable to get the previous/next values in the subscription, then use next for the currentValue

public myForm = new FormGroup({
  myInput: new FormControl('', [Validators.required])
});
public autocompleteItems: string[] = [];

ngOnInit() {
  this.myForm.get('myInput').valueChanges
    .pipe(pairwise())
    .pipe(
      takeUntil(this.unsubscribe),
      switchMap((inputString: string) => this.mySearchService.search(inputString)))
    .subscribe(([prev, next]: [any, any]) => {
      this.autocompleteItems = next;
      console.log(this.autocompleteItems);
    });
}
Kinglish
  • 23,358
  • 3
  • 22
  • 43