0

I am using ng-select with Angular 7 and have the following component:

export class PostComponent {

  selectedCategoryId: number;

  categories$: Observable<CategoryModel[]>;

  constructor(private categoryService: CategoryService) { }

  ngOnInit() {

    this.categories$ = this.getCategories('');

  }

  getCategories(term: string): Observable<CategoryModel[]> {

    return this.categoryService.get(term).pipe(map((envelope: Envelope<CategoryMessage.Response>) => 

      envelope.result.map((response: CategoryMessage.Response) => { 

        return {
          id: response.id, 
          name: response.name
        };

      })));

  }

}

The categoryService returns Categories where Category Name contains the term.

On the template I have the following:

<ng-select 
   class="select"
   [items]="categories$ | async"
   [addTag]="true"
   bindLabel="name"
   bindValue="id"
   [multiple]="false"
   [(ngModel)]="selectedCategoryId">
</ng-select>

Question

  1. How can I call the API, through the service, only when the typed word has 3 or more letters? This would be to prevent getting thousands of categories.

  2. How can I integrate my code to use typeahead?

ahbon
  • 502
  • 4
  • 19
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481

1 Answers1

0

Template:

<ng-select 
   class="select"
   [items]="categories$ | async"
   [addTag]="true"
   bindLabel="name"
   bindValue="id"
   [multiple]="false"
   [(ngModel)]="selectedCategoryId"
   (ngModelChange)="onModelChange($event)">
</ng-select>

Angular component:

public onModelChange(term) {
   if (term && term.length >= 3) {
      this.getCategories(term).subscribe(categories => {
         // You can put you logic here...
      });
   }
}

EDIT: Maybe you could also have a look at debounce function that is very usefull to prevent many requests during a typehead. Please check this example.

ahbon
  • 502
  • 4
  • 19
  • Why ngModelChange instead of typeahead? Should I not use typeahead for autocomplete with server data? – Miguel Moura Mar 13 '19 at 01:03
  • The example you posted is for AngularJs not Angular 6+ – Miguel Moura Mar 13 '19 at 01:05
  • The best practice is to use `debounceTime`given by `rxjs` to limit the amount of http request. `ngModelChange` only notifies when your model has been updated. Check this [example](https://medium.com/aviabird/rxjs-reducing-number-of-api-calls-to-your-server-using-debouncetime-d71c209a4613) Angular 2 – ahbon Mar 13 '19 at 14:24