简体   繁体   中英

How to move focus to a list item on using the down arrow key on a custom search field?

I am building a custom autosuggest feature in my angular application following THIS tutorial.

It basically includes an HTML input tag where the user can type in the query field, followed by an unordered list that holds the list of matched results.

The issue with this design is that once the user types in a string in the query field and the matching results are displayed below, pressing the down array key does not bring the focus to the first result in the list to select it. The option can now only be selected by clicking on the list item.

For eg:

If the query string is "jac", the list of results displayed are "jacob", "jack", "jaccard" etc. On pressing the down arrow key I want the focus to be shifted to the first result which is "jacob".

Here's the code:

search.component.html


<div class="input-group">
  <input type="text" class="form-control" [formControl]="queryField" value="queryField" id="companyName"
    placeholder="Company Name">
  <span class="input-group-addon">
    <button class="arrow" type="submit" (click)="getCompanyDetails()">
      <span>
        <img src="../../assets/ic-arrow-forward.svg" class="ic_arrow_forward">
      </span>
    </button>
  </span>
  <ul class="filter-select">
    <li class="filter-select-list" *ngFor="let result of searchResults; let i = index" (click)="listClick(result)">
      <span class="comp-name">{{ result.companyName }}</span>
  </ul>
</div>

search.component.ts

listClick(selectedCompany) {
    this.searchResults = null;
    this.service.companyName = selectedCompany.companyName;
    this.queryField.setValue(selectedCompany.companyName, {emitEvent: false});
  }

  ngOnInit() {
    this.queryField.valueChanges
      .pipe(debounceTime(200))
      .pipe(distinctUntilChanged())
      .pipe(switchMap((queryField) => this.service.search(queryField)))
      .subscribe(
        (response) => {
          this.searchResults = response;
        });
  }

How can I achieve this in angular, preferably without using jQuery.

Thanks in advance!

Have a look at ng2-ui/auto-complete

Great component, you can refer it to build your custom component.

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM