How can I force Angular 7+ Material Autocomplete to enter letters only provided by a data source?

陌路散爱 提交于 2019-12-04 17:06:40

I've solved this problem with a custom validator. If you want to see it, here,..

In the list but case sensitive:

Wrong Value

Everything is OK

It might be more efficient to trap the key entry at input time by adding a keydown handler to the input. Then look ahead at what the value would be and compare it to the list, 'cancelling' the event if necessary. Crudely:

<input (keydown)="keydownHandler($event)" ...


keydownHandler(event: KeyboardEvent) {
  const character = event.key;
  if (character.length === 1) {

    let value = this.myForm.controls.myControl.value;
    if (typeof value === 'object') {
      value = value.name;
    }

    value = (value + character).toLowerCase();

    if (!this.options.some(option => option.name.toLowerCase().indexOf(value) === 0)) {
      event.preventDefault();
    }
  } 
}

This works with any kind of form.

Stackblitz

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