angular - 是否可以在 MatAutoComplete 上以角度显示管道?
问题描述
我很好奇是否可以在 displayFn 中使用管道。我将它用于国家选择,但为了避免处理保存值中的语言,我只想使用 Aplha2 国家代码。因此,在给定的代码示例中,我选择将 mat-option 上的值设置为对象的国家代码。
我尝试在显示功能中使用服务,但它始终未定义,我认为这是因为该功能是作用域的。因此,组件中具有显示功能的任何内容都将为空。
在 html 模板中:
<mat-form-field class="fill">
<mat-label >Country</mat-label>
<input matInput placeholder="Search Countries" [matAutocomplete]="auto" formControlName="country">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayCountryFn">
<mat-option *ngIf="countriesLoading" class="is-loading">Loading...</mat-option>
<ng-container *ngIf="!countriesLoading">
<mat-option *ngFor="let cc of filteredCountries" [value]="cc.countryCode"> {{cc.countryCode | a2Country}} </mat-option>
</ng-container>
</mat-autocomplete>
</mat-form-field>
在 component.ts 文件中
export class SomeComponent{
...
constructor(private countryService: CountryService){}
...
displayCountryFn(cc: String){
//cc is the contryCode
//this.countryService is always undefined in this case
if(this.countrySerivce !=null){
return this.countryService.fromAplha2(cc);
}
return cc;
}
}
如果需要,我不介意做一些黑客攻击。因此,假设我在输入中键入 DK,并且值只是更改为丹麦(以本地化语言),但是在这种情况下,我必须注意因为输入已经有一个侦听器,该侦听器对搜索国名的值进行了侦听。
解决方案
实际上,您需要将组件的范围绑定到显示功能。你可以将你的显示函数定义为一个箭头函数,这样你的函数的作用域就是你的组件的作用域:
displayCountryFn = (cc: string) => {
//cc is the contryCode
if(this.countrySerivce != null){
return this.countryService.fromAplha2(cc);
}
return cc;
}
请参见此处:使用 Angular 5 在 Angular Material Autocomplete displayWith 中绑定“this”
推荐阅读
- python - Python代码由于未知原因忽略了if-else语句
- r - 编写一个循环以分别对每一列应用 ifelse(在 R 中)
- python - Plotly 和 Google Colab
- c# - 如何基于选项卡控件创建自定义用户控件,使选项卡项具有特定格式
- c# - ASP.NET Core 5 - 具有动态字段数的表单
- android - 我不能使用 Json 对象和凌空
- node.js - 在 webpack 重新编译时触发 websocket 服务器发送到客户端
- arrays - 如何使用 C 循环打印数组
- python - 使用 json 在 Python 中分配值的字符串
- ruby - 尝试从变量中减去哈希中的所有值