加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度材料自动完成不起作用,没有显示错误

发布时间:2020-12-17 17:34:12 所属栏目:安全 来源:网络整理
导读:我已经实现了自动完成功能,没有错误,一切似乎都没问题,但绝对没有任何反应.我在输入字段中输入了一些内容,似乎没有任何操作,控制台中没有显示任何内容. HTML form mat-form-field input type="text" matInput [formControl]="myControl" [matAutocomplete]="
我已经实现了自动完成功能,没有错误,一切似乎都没问题,但绝对没有任何反应.我在输入字段中输入了一些内容,似乎没有任何操作,控制台中没有显示任何内容.

HTML

<form>
    <mat-form-field>
      <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
    </mat-form-field>

    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let n of testValues" [value]="n">
        {{n}}
      </mat-option>
    </mat-autocomplete>
  </form>

TS

import { MatAutocomplete } from '@angular/material/autocomplete';
import { FormControl } from '@angular/forms';
...
public testValues = ['one','two','three','four'];
public myControl: FormControl;
...
constructor() {
    this.myControl = new FormControl();
}

编辑:我已经导入了

import {MatAutocompleteModule} from '@angular/material/autocomplete';

在我的app模块中.

材料版本 –

"@angular/material": "^5.0.0-rc.2",

解决方法

您缺少.ts中的过滤方法

您必须以这种方式订阅myControl valueChanges:

this.myControl.valueChanges.subscribe(newValue=>{
    this.filteredValues = this.filterValues(newValue);
})

因此,每当您的表单控件值发生更改时,您都会调用自定义的filterValues()方法,该方法应如下所示:

filterValues(search: string) {
    return this.testValues.filter(value=>
    value.toLowerCase().indexOf(search.toLowerCase()) === 0);
}

所以你使用你的testValues数组作为基础数组,并在你的html中使用filteredValues数组:

<mat-option *ngFor="let n of filteredValues" [value]="n">
    {{n}}
</mat-option>

过滤不是自动的,您必须使用自定义方法来过滤选项.希望能帮助到你

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读