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

前端之家收集整理的这篇文章主要介绍了角度材料自动完成不起作用,没有显示错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经实现了自动完成功能,没有错误,一切似乎都没问题,但绝对没有任何反应.我在输入字段中输入了一些内容,似乎没有任何操作,控制台中没有显示任何内容.

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>

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

猜你在找的Angularjs相关文章