简体   繁体   中英

Translate text in Ts file - Angular Ngx Translation

I want to translate text exist in my typescript file so each time I want to change the language while I am using the application the text should change (example change language from english to frensh). I tried the following code but didn't works

this.translate.get('example').subscribe(res => { this.title = res.title }

Also I tried this and It worked fine but I don't want to add same code in different components every time I want to translate something in typescript file when I change from language to another

this.translate.onLangChange.subscribe(() => {
                this.translate.get('example').subscribe(res => { this.title = res.title }
        });

您应该将翻译服务放在 app.component 中并在那里进行所有翻译,这样您就无需在其他任何地方复制

Try constructing your title value this way :

this.title$: Observable<string> = this.translate.onLangChange.pipe(
  switchMapTo(this.translate.get('example')),
  map((result: string) => result.title)
)

Then use async pipe in your html instead of subscribing in your ts file.

If you need to translate your value programmatically. You need to listen to onLangChange each time. You could try to abstract this logic in a dedicated service.

My advice is to try to use the translate pipe instead of trying to set the value programmatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM