0

This is the form that I am using:

<form [formGroup]="searchForm" id="searchForm">
   <mat-form-field>
      <input
      matInput
      type="text"
      name="awesome"
      id="awesome"
      [formControl] = "formCtrl"
      [matAutocomplete] = "auto"
      value="{{ awesomeText }}"
      [matAutocomplete]="auto">
      <mat-autocomplete #auto = "matAutocomplete">
         <mat-option *ngFor = "let res of result | async" [value] = "res">
         {{res}}
         </mat-option>
      </mat-autocomplete>
   </mat-form-field>
</form>

And this is inside constructor():

this.formCtrl = new FormControl();
this.formCtrl.valueChanges.subscribe((newValue) => {
    this.result = this.find(newValue);
    console.log('yes');
});

The yes is printing so I know that this is working but mat-autocomplete does not show anything. The result variable is also updating as I can see it printing on console. I am not able to understand why the searched values are not being displayed.

I would appreciate any help!

Edit

This is the find() method:

find(val: string): string[] {
    const matchFound = [];

    for (let i = 0; i < dataJson.length; i++) {
        if (dataJson[i].text.toLowerCase().startsWith(val) || dataJson[i].text.startsWith(val)) {
            matchFound.push(dataJson[i].text);
        }
    }

    console.log('matches ' + matchFound);
    return matchFound;
}
Tommy
  • 2,355
  • 1
  • 19
  • 48
Panda
  • 499
  • 11
  • 22

1 Answers1

0

You should assign Observable of string array to the this.result. But you are assigning normal string array. async pipe works with observable not with the normal array. And in the template you need below change

From

<mat-option *ngFor="let res of result | async" [value]="res">{{res}}</mat-option>

To

<mat-option *ngFor="let res of result | async" [value]="res.text">{{res.text}}</mat-option>

Typescript changes

ngOnInit() {
  this.result = this.myControl.valueChanges.pipe(
    startWith(""),
    map(value => this.find(value))
  );
}

find(val: string): {
  id: number,
  text: string
}[] {
  const matchFound: {
    id: number,
    text: string
  }[] = [];

  for (let i = 0; i < this.dataJson.length; i++) {
    if (
      this.dataJson[i].text.toLowerCase().startsWith(val) ||
      this.dataJson[i].text.startsWith(val)
    ) {
      matchFound.push(this.dataJson[i]);
    }
  }

  console.log("matches " + matchFound);
  return matchFound;
}

Working stackblitz

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56