首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >能不能在DisplayWith上用MatAutoComplete作棱角形的管子?

问能不能在DisplayWith上用MatAutoComplete作棱角形的管子?
EN

Stack Overflow用户
提问于 2020-07-27 07:28:22
回答 1查看 457关注 0票数 1

我很好奇是否可以在displayFn中使用管道。我使用它来选择国家,但为了避免在保存的值中处理语言,我只想使用Aplha2国家代码。因此,在给定的代码示例中,我选择将mat选项上的值设置为对象的国家代码。

我试图在display函数中使用一个服务,但它始终是未定义的,而且我认为它是因为函数的作用域。因此,组件中的任何东西,即显示函数,都将为空。

在html模板中:

代码语言:javascript
复制
<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文件中

代码语言:javascript
复制
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,值就会更改为丹麦(在本地化语言中),但是在这种情况下,我必须小心,因为输入已经有了一个侦听器,用于搜索国家名称。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-16 10:33:20

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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63110588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档