Angular 5 :Trigger mat-autocomplete on pressing a

2019-06-10 21:24发布

I am trying to come up with something like the tagging feature on Facebook i.e whenever '@' key is pressed my autocomplete should be triggered and I should be able to see the option corresponding to the data typed post '@'.

I am unable to bind the autocomplete on keydown(or any key event)

Any suggestion on how to achieve this functionality would be appreciated, My last resort is coming up with my own autocomplete module

1条回答
疯言疯语
2楼-- · 2019-06-10 21:41

You can do the following to accomplish this.

Create a ViewChild to get reference to the MatAutocompleteTrigger

@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;

Create a HostListener to set the formControl value to @ and open the panel when the @ key is pressed.

@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
    if (event.key == '@') {
      this.stateCtrl.setValue('@');
      this._auto.openPanel();
    }
  }

Stackblitz

In this stackblitz, click the view to set focus or the event will not trigger the HostListener

https://stackblitz.com/edit/angular-4x3zte?embed=1&file=app/autocomplete-overview-example.ts

查看更多
登录 后发表回答