typescript 角度材料自动完成不起作用,未显示错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48337188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular material autocomplete not working, no errors shown
提问by Simeon Nakov
I've implemented my autocomplete, no errors, everything seems ok however absolutely nothing happens. I enter something in the input field and no action seems to happen, nothing is shown in the console.
我已经实现了我的自动完成,没有错误,一切看起来都很好,但是绝对没有任何反应。我在输入字段中输入了一些东西,但似乎没有任何动作发生,控制台中也没有显示任何内容。
HTML
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
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();
}
EDIT: I have imported
编辑:我已经进口
import {MatAutocompleteModule} from '@angular/material/autocomplete';
in my app module.
在我的应用程序模块中。
Version of material -
材料版本 -
"@angular/material": "^5.0.0-rc.2",
回答by Gianluca Paris
You are missing a filter method in your .ts
您缺少过滤器方法 .ts
You have to subscribe to your myControl
valueChanges
this way:
您必须以myControl
valueChanges
这种方式订阅:
this.myControl.valueChanges.subscribe(newValue=>{
this.filteredValues = this.filterValues(newValue);
})
So everytime your form control value changes you call your custom filterValues()
method, that should look like:
因此,每次您的表单控件值更改时,您都会调用自定义filterValues()
方法,它应该如下所示:
filterValues(search: string) {
return this.testValues.filter(value=>
value.toLowerCase().indexOf(search.toLowerCase()) === 0);
}
So you use your testValues
array as a base array, and your filteredValues
array in your html:
所以你使用你的testValues
数组作为一个基本数组,你的filteredValues
数组在你的 html 中:
<mat-option *ngFor="let n of filteredValues" [value]="n">
{{n}}
</mat-option>
Filtering is not automatic, you have to use your custom method to filter the options. Hope it helps
过滤不是自动的,您必须使用自定义方法来过滤选项。希望能帮助到你