首页 > 解决方案 > 是否可以在 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,并且值只是更改为丹麦(以本地化语言),但是在这种情况下,我必须注意因为输入已经有一个侦听器,该侦听器对搜索国名的值进行了侦听。

标签: angularangular-material

解决方案


实际上,您需要将组件的范围绑定到显示功能。你可以将你的显示函数定义为一个箭头函数,这样你的函数的作用域就是你的组件的作用域:

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”


推荐阅读