I have a parent component that has a child component, I want to translate the text based on the user language I get it from an api.
Here is my translation pipe transform method:
transform(value : string, args: any[]) : any
{
if (!value) return ;
return this._translationService.translate(value) ;
}
Translation Service
export class TranslationService {
private _currentLang: string = 'en';
public use(langId: number): void {
this._currentLang = langId == 0 ? 'fr' : 'en';
}
public translate(key: string) {
//tranlsation happens here
}
}
Here is the Parent component where its getting the langId in ngOnInit()
ngOnInit() : void
{
this._langService.getLanguageId(this.userId)
.subscribe( langId=> { this._translationService.use(langId); });
}
}
In Parent and Child Component Templates I would have used the pipe as this:
<div >{{ 'Caption_Key' | translation }}</div>
The child Component is translating the captions before setting the langId of translation service. However the parent component translation is working fine. I see the call is async, but how can I assure that child components would have the correct language before transformation happens.
I tried to use EventEmitter
and emitting an event when calling the use(langId) in the service, then made the pipe to subscribe to the event, but that didn't work...
If the child component relies on the translation to function properly, then it may be worth considering not instantiating the child component until you know the language.
this._langService.getLanguageId(this.userId)
.subscribe(langId => {
this._translationService.use(langId);
this.translationSet = true;
});
}
<child-component *ngIf="translationSet"></child-component>
EDIT:
A more scalable approach would be to have the this._translationService.use
do a translationSubject.emit(language)
after setting the language, and having all components subscribe to the language setting.