我已经实现了我的自动完成,没有错误,一切似乎都正常,但绝对没有任何反应。我在输入字段中输入了一些内容,但似乎没有任何操作发生,控制台中也没有显示任何内容。
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';
在我的应用模块中。
Material 版本 -
"@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>
过滤不是自动的,您必须使用自定义方法来过滤选项。希望对你有帮助
关于 Angular Material 自动完成不起作用,没有显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48337188/