本文介绍了如何停止mat-autocomplete以使自定义用户输入值与给定选项分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用来自material.angular.io的mat-auto完整组件.默认行为是用户可以输入任何值以及它提供的选项供您选择.您也可以将输入添加到选定的值.您可以在此处查看示例. https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-简单-example.html

I am using mat-auto complete component from material.angular.io. The default behavior is user can input any value as well as it gives options to choose from. Also you can add your input to chosen values.You can check example here.https://stackblitz.com/angular/ngmvgralayd?file=app%2Fautocomplete-simple-example.html

这是我用于生成自动完成输入字段的代码.

here is the code I am using for generating auto complete input field.

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto" disabled="true">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

但是我希望表单字段仅接受给定选项中的值,并希望防止用户输入除给定选项之外的任何值.如何实现呢?就像具有自动完成功能的选择输入一样.

But I want the form field to take only values from the given option and want to prevent from entering any values by users apart from given option. How to achieve this? It is like select input with auto complete feature.

推荐答案

标记:

<md-input-container class="full-width">
<input mdInput [mdAutocomplete]="autoData"
       #searchMyData
       formControlName="myControl"
       (keyup)="changeMyControl()">
</md-input-container>
<md-autocomplete #autoData="mdAutocomplete">
<md-option
    *ngFor="let option of options"
    [value]="option.name"
    (onSelectionChange)="onSelectedOption($event.source.selected, option.id);">
    {{ option.name }}
</md-option>
</md-autocomplete>

组件:

selectedOption;
changeMyControl(): void {
    if (isUndefined(this.selectedOption) {
        // also check selected item and entered text are not same
        this.myForm.get('myControl').setErrors({'incorrect': true});
    }
}

onSelectedOption(isSelected: boolean, id: number): void {
    if (isSelected) {
        setTimeout(() => {
            const option = this.options.filter(bt => bt.id === id);
            if (option.length > 0) {
                this.selectedOption= option[0];
               // patch formcontrol value here
            }
        }, 200);
    }
}

这篇关于如何停止mat-autocomplete以使自定义用户输入值与给定选项分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-25 22:44
查看更多