我很好奇是否可以在displayFn中使用管道。我使用它来选择国家,但为了避免在保存的值中处理语言,我只想使用Aplha2国家代码。因此,在给定的代码示例中,我选择将mat选项上的值设置为对象的国家代码。
我试图在display函数中使用一个服务,但它始终是未定义的,而且我认为它是因为函数的作用域。因此,组件中的任何东西,即显示函数,都将为空。
在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,值就会更改为丹麦(在本地化语言中),但是在这种情况下,我必须小心,因为输入已经有了一个侦听器,用于搜索国家名称。
发布于 2021-02-16 10:33:20
实际上,您需要将组件的作用域绑定到显示函数。您可以将显示函数定义为箭头函数,这样您的函数的作用域将是组件的作用域:
displayCountryFn = (cc: string) => {
//cc is the contryCode
if(this.countrySerivce != null){
return this.countryService.fromAplha2(cc);
}
return cc;
}见此处:Binding 'this' in Angular Material Autocomplete displayWith using Angular 5
https://stackoverflow.com/questions/63110588
复制相似问题