Ian
Ian

Reputation: 351

Display autocomplete option of array of object in angular 6

I am trying to implement Material Autocomplete in angular 6. I trying to implement autocomplete for vendor data instead of drop down. However, I am stuck at error saying not iterable on object. I follow the tutorial of stackblitz https://stackblitz.com/edit/am-all-imports-kojajh?file=app%2Fapp.component.ts. Still got these errors. My component.ts file

export interface IVendor {
    VendorId: string;
    VendorName: string;
}

--------------------Var declarations-------
filterVendor: Observable<IVendor[]>;
VendorCtrl = new FormControl();
vendorArr = [];

    vendors: IVendor[] = [
        { "VendorId": "1234", "VendorName": "anjan" },
        { "VendorId": "12344", "VendorName": "asus" },
        { "VendorId": "12345", "VendorName": "sujan" },
        { "VendorId": "12347", "VendorName": "sudip" },
        { "VendorId": "12349", "VendorName": "ram" },
        { "VendorId": "12340", "VendorName": "shyam" },
        { "VendorId": "12341", "VendorName": "hari" },
        { "VendorId": "12342", "VendorName": "ganesh" },
        { "VendorId": "12343", "VendorName": "kesab" },
        { "VendorId": "12348", "VendorName": "laxman" },
        { "VendorId": "12346", "VendorName": "laxmi" },
        { "VendorId": "123421", "VendorName": "rani" },
    ]

ngOnInit() {
   this.filterVendor = this.VendorCtrl.valueChanges
          .pipe(
              startWith(''),
              map(option => option ? this._filterVendor(option) : this.vendors.slice())

          );
}

_filterVendor(name: string) {
        return this.vendors.filter(opt =>
            opt.VendorName.toLowerCase().indexOf(name.toLowerCase()) === 0);
    }

displayFn(ven?: IVendor): string | undefined {
        return ven ? ven.VendorName : undefined;
    }

Then html file

<mat-form-field>
  <input matInput placeholder="VendorName" [matAutocomplete]="auto" [formControl]="VendorCtrl" 
                      formControlName="VendorId" />
     <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
      <mat-option *ngFor="let vendor of filterVendor" [value]="vendor.VendorId">
         <span>{{vendor.VendorName}}</span> 
       </mat-option>
   </mat-autocomplete>
</mat-form-field>

However it throws ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. What does it mean? How can it be solved?

Upvotes: 3

Views: 648

Answers (1)

Andreas
Andreas

Reputation: 76

You're missing the | async pipe in *ngFor="let vendor of filterVendor".

So, with replacing it with *ngFor="let vendor of filterVendor | async" you should be good to go.

See:

https://angular.io/api/common/AsyncPipe

Upvotes: 2

Related Questions