角度材质 displayWith 不适用于 ngx-translate

Sha*_*iby 5 javascript rxjs typescript ngx-translate angular

我在 mat-autocomplete 中使用 [displayWith] 指令。当我手动选择值时它工作正常,但当我重新加载页面时我没有得到翻译。翻译所需的参数是从 ngOnInit 中的查询参数异步加载的。所以我依赖异步参数,但我的 displayFunction() 是同步函数。怎么解决呢?

如果没有 [displayWith] 功能,一切正常,但没有翻译(它只是显示我不想要的纯值)。所以我确信其余代码是正确的。

我的垫子自动完成:

<mat-form-field [formGroup]="cityForm"
                appearance="outline"
                floatLabel="never"
                color="primary">
  <mat-icon matPrefix>location_on</mat-icon>
  <input type="text" placeholder="{{ 'job_offer_search_bar.job-offer-search-bar-city-form.placeholder' | translate }}"
         aria-label="Number" matInput
         formControlName="cityControl" [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onSelectionChanged($event.option.value)"
                    [displayWith]="displayFn.bind(this)">
    <mat-option>
      {{ 'job_offer_search_bar.job-offer-search-bar-city-form.all' | translate }}
    </mat-option>
    <mat-option *ngFor="let city of filtredCities | async" [value]="city">
      {{ 'job_offer_search_bar.job-offer-search-bar-city-form.city' | translate:"{ city: '" + city +"' }"}}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)

我的 displayWith 函数如下:

displayFn(val: string){
    if (!val) return '';
    let stringToReturn;
    this.translate.get('job_offer_search_bar.job-offer-search-bar-city-form.city', {city: val}).subscribe(value => {
      console.log('inside subscribe', value);
      stringToReturn = value;
    });
    console.log('after sub', stringToReturn);
    if (stringToReturn != undefined) {
      return stringToReturn;
    } else {
      return 'Sorry, value has not been translated';
    }
Run Code Online (Sandbox Code Playgroud)

Console.log in subscribe在 后调用console.log after subscribe。因此,订阅是在我获得翻译参数后进行的,因此在我返回后...我需要一些技巧或技巧来传递翻译后的字符串作为返回。

我认为有一种方法可以做到这一点。任何帮助将不胜感激。

Sha*_*iby 0

问题的解决很棘手。我必须在 mat-form-field 上使用 *ngIf 来等待翻译后的标签:

<mat-form-field *ngIf="isReady$ | async" [formGroup]="cityForm"
Run Code Online (Sandbox Code Playgroud)

翻译完成后应该满足条件,所以我必须在 ngOnInit 中执行此操作:

 this.isReady$ = this.translate.get('translate_id').pipe(mapTo(true));
Run Code Online (Sandbox Code Playgroud)

因此,现在在翻译服务返回翻译之前不会显示元素。这是一个解决方法,但我还没有找到其他解决方案。