我想通过开始输入(不滚动)显示国家名称。
这是我尝试过的:Stackblitz
将列出所有国家/地区,但是如果我键入内容,则什么也不会发生。
我该如何解决?
您非常接近,但是由于您所在的国家/地区列表同时具有“名称”和“代码”,因此您必须编辑_filter函数以根据所需的值“名称”进行过滤
查看此Angular材料example和随附的StackBlitz
,您需要创建的是管道过滤器:
喜欢
import { Pipe,PipeTransform } from '@angular/core';
export interface Country{
name: String,code: String
}
@Pipe({ name: 'myCountry' })
export class CountryPipe implements PipeTransform {
transform(allCountries: Country[],search: string) {
if (search){
return allCountries.filter((country:Country) => country.name.includes(search));
}
return allCountries;
}
}
将其添加到您的应用模块中的声明中,例如:
declarations: [AutocompleteFilterExample,CountryPipe],
当您将其添加到您的 ngFor 中时,这样可以过滤输入内容:
<mat-form-field class="example-full-width">
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option
*ngFor="let country of (countries | myCountry:myControl.value )"
[value]="country.name">
{{country.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
,
要给出一个简单的答案,您的问题仅在于Rydyell的这一行。
return this.countries.filter(option => option.toLowerCase().includes(filterValue));
如果您为国家/地区定义接口,TypeScript确实可以帮助您解决此问题。
option
这是一个对象({"name": "Afghanistan","code": "AF"}
),您需要过滤属性,而不是整个对象-像这样:
return this.countries.filter(option => option.name.toLowerCase().includes(filterValue));