how to format ng bootstrap typeahead results by numerically ascending

梦想的初衷 提交于 2020-02-06 19:00:04

问题


I'm currently using ng-boostrap specifically the typeahead portion to display the results for my typeahead.

Everything is working great except that i can't get it to format my results numerically to show the least amount to highest amount that matched.

so if i had a list like this..

numbers = [12, 22, 43, 11, 1, 4, 77, 111];

I would want the 1 to pop up first and 11, 1111 after and so on...

here is what my code looks like now...

  formatter = (result: string) => result.orderBy(numbers);

  searchNumber = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term === '' ? []
        : this.numbers.filter(v => v.indexOf(term) > -1))
    )

my template:

  <input
     class="form-control"
     name="billNumberDigitInput"
     type="text"
     placeholder="####"
     formControlName="number"
     [ngbTypeahead]="searchNumber"
     [resultTemplate]="rt"
     [resultFormatter]="formatter"
     required/>
  <ng-template #rt let-r="result" let-t="term">
       <ngb-highlight [result]="r" [term]="t"></ngb-highlight>
  </ng-template>

回答1:


simply sort the array of suggestions

  searchNumber = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term === '' ? []
        : this.numbers.filter(v => v.indexOf(term) > -1)).sort()
    )

with

numbers = [12, 22, 43, 11, 1, 4, 77, 111];

you would get

numbers = [1, 11, 111, 12, 22, 4, 43, 77];

I wouldn't name it sorting numericaly. It's rather sorting numbers as strings. If u want to get result as

numbers = [1, 4, 11, 12, 22, 43, 77, 111];

Then just need to provide comparison function to sort method

  searchNumber = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term === '' ? []
        : this.numbers.filter(v => v.indexOf(term) > -1)).sort((a, b) => a - b)
    )


来源:https://stackoverflow.com/questions/57364927/how-to-format-ng-bootstrap-typeahead-results-by-numerically-ascending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!