首页 > 解决方案 > MatAutoComplete - 更改语言时更新显示在 displayWith 中的属性

问题描述

我目前正在使用 Angular 11,我注意到当我更改应用程序语言(通过按钮)时,mat-autocompletes选择的值没有翻译,但自动完成的所有可用值都正确翻译。

在此处输入图像描述

正如您在上面看到的,在其中一个自动完成中,我有一个“类型”类对象的列表。这些对象有一个名为“label_culture_aware”的属性,用于根据我们使用的语言返回正确的属性。(例如,如果我们使用法语,则返回“label_fr”属性,如果使用英语,则返回“label_en”)

这是我的代码:

html

<div class="col-12 col-md-3 space-between-col" formGroupName="autocomplete">
                <mat-form-field  [floatLabel]="floatLabel" [appearance]="appearance">
                    <mat-label>{{ 'committee.type' | translate }}</mat-label>
                    <input  matInput
                            [matAutocomplete]="TypeAutoComplete"
                            formControlName='type'
                    />
                </mat-form-field>
                <mat-autocomplete   #TypeAutoComplete="matAutocomplete"
                                    [displayWith]="displayTypeForAutocomplete"
                >
                    <mat-option *ngIf="autocomplete.type.fetching" class="is-loading">
                        <mat-spinner diameter="50"></mat-spinner>
                    </mat-option>
                    <ng-container *ngIf="!autocomplete.type.fetching">
                        <mat-option *ngFor="let type of autocomplete.type.values" [value]="type">
                            <span>{{ type.label_culture_aware }}</span>
                        </mat-option>
                    </ng-container>
                </mat-autocomplete>
</div>

打字稿

   /**
     * Display selected options in the Auto-Complete input
     */
    displayTypeForAutocomplete(type: Type)
    {
        if  (type)
        {
            return type.label_culture_aware;
        }
    }
// Type class
public get label_culture_aware(): string
    {
        return TranslateHelpersService.getLocalizedString   (   this.label_fr,
                                                                this.label_en
                                                            );
    }

我想问题是由于[displayWith]属性一旦初始化就不会重构,这与{{ type.label_culture_aware }}我的 html 模板中的相反。

所以我的问题是:有没有办法在[displayWith]更改语言时更新值?

标签: javascriptangularmat-autocomplete

解决方案


推荐阅读