[英]Angular 7 ngx-translate doesn't remember the language after refresh
[英]Angular material displayWith isn't working with ngx-translate
我在 mat-autocomplete 中使用 [displayWith] 指令。 當我手動選擇值時它工作正常但是當我重新加載頁面時我沒有得到翻譯。 轉換所需的參數是從 ngOnInit 中的查詢參數異步加載的。 所以我依賴 async 參數,但我的 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>
我的 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';
}
Console.log in subscribe
之后的console.log after subscribe
調用。 所以訂閱是在我獲得翻譯參數后進行的,所以在我返回之后......我需要一些技巧或提示來傳遞我翻譯的字符串作為回報。
我認為有辦法做到這一點。 任何幫助都會得到認可。
在大多數情況下,Observable是異步函數。 根據您的實現,您可以使用translate.instant
displayFn(val: string) {
const defaultMessage = 'Sorry, value has not been translated';
return val
? this.translate.instant('job_offer_search_bar.job-offer-search-bar-city-form.city', { city: val }) || defaultMessage
: '';
}
如果在加載轉換文件之前調用了即時函數,則它將返回undefined。
編輯:
displayFn(val: string) {
const translate$ = this.translate.get('job_offer_search_bar.job-offer-search-bar-city-form.city', { city: val }).pipe(
map(translatedText => translatedText || 'Sorry, value has not been translated')
)
return val
? translate$
: of('');
}
[displayWith]="displayFn.bind(this) | async"
解決這個問題很棘手。 我不得不在mat-form-field上使用* ngIf來等待我的翻譯標簽:
<mat-form-field *ngIf="isReady$ | async" [formGroup]="cityForm"
翻譯完成后應該滿足條件所以我必須在ngOnInit中執行此操作:
this.isReady$ = this.translate.get('translate_id').pipe(mapTo(true));
所以現在,在從翻譯服務返回翻譯之前,元素沒有顯示出來。 這是一種解決方法,但我還沒有找到其他解決方案。
如果您使用changeDetection: ChangeDetectionStrategy.OnPush
策略
您可以將AfterViewChecked
工具添加到您的組件中,並且
在ngAfterViewChecked
鈎子上,添加下一個代碼:
ngAfterViewChecked() {
this._translateService.onLangChange.subscribe(() => {
this._changeDetectorRef.detectChanges()
});
}
在這種方法中,您無需在模板中做任何事情。
它對我有用。 享受。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.