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

Sim*_*kov 7 autocomplete typescript angular-material angular-material2 angular

我已经实现了自动完成功能,没有错误,一切似乎都没问题,但绝对没有任何反应.我在输入字段中输入了一些内容,似乎没有任何操作,控制台中没有显示任何内容.

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>
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

编辑:我已经导入了

import {MatAutocompleteModule} from '@angular/material/autocomplete';
Run Code Online (Sandbox Code Playgroud)

在我的app模块中.

材料版本 -

"@angular/material": "^5.0.0-rc.2",
Run Code Online (Sandbox Code Playgroud)

Gia*_*ris 10

你错过了一个过滤方法 .ts

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

this.myControl.valueChanges.subscribe(newValue=>{
    this.filteredValues = this.filterValues(newValue);
})
Run Code Online (Sandbox Code Playgroud)

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

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

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

<mat-option *ngFor="let n of filteredValues" [value]="n">
    {{n}}
</mat-option>
Run Code Online (Sandbox Code Playgroud)

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