Angular 5:按下特定键时触发垫自动完成 [英] Angular 5 :Trigger mat-autocomplete on pressing a particular key

查看:25
本文介绍了Angular 5:按下特定键时触发垫自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Facebook 上想出类似标记功能的功能,即每当按下@"键时,我的自动完成功能就会被触发,并且我应该能够看到与键入的帖子@"对应的选项.

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 '@'.

我无法在 keydown(或任何键事件)上绑定自动完成

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

推荐答案

您可以执行以下操作来完成此操作.

You can do the following to accomplish this.

创建一个 ViewChild 以获取对 MatAutocompleteTrigger

Create a ViewChild to get reference to the MatAutocompleteTrigger

@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;

创建一个HostListener,设置formControl值为@,当@键为@键时打开面板按下.

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

在本次stackblitz中,点击view设置焦点否则事件不会触发HostListener

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

这篇关于Angular 5:按下特定键时触发垫自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆