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

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

问题描述

我试图提出类似Facebook上的标记功能的方法,即每当按下'@'键时,我的自动完成功能应被触发,并且我应该能够看到与数据类型为'@'相对应的选项./p>

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

任何有关如何实现此功能的建议将不胜感激,我最后的选择是提出自己的自动完成模块

解决方案

您可以执行以下操作来实现此目的.

创建一个ViewChild以获得对MatAutocompleteTrigger

的引用

@ViewChild(MatAutocompleteTrigger) _auto: MatAutocompleteTrigger;

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

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

Stackblitz

在此堆叠闪电击中,单击视图以设置焦点,否则事件将不会触发HostListener

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

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

解决方案

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

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

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