Angular 9: I18n In TypeScript
Answer :
Check this blog https://blog.ninja-squad.com/2019/12/10/angular-localize/
@Component({ template: '{{ title }}' }) export class HomeComponent { title = $localize`You have 10 users`; }
And
You have to manually add it to your messages.fr.xlf
<trans-unit id="6480943972743237078"> <source>You have 10 users</source> <target>Vous avez 10 utilisateurs</target> </trans-unit>
don't forgot re serve your angular application.
UPDATE FOR ID
@Component({ template: '{{ title }}' }) export class HomeComponent { title = $localize`:@@6480943972743237078:`; }
https://github.com/angular/angular/blob/252966bcca91ea4deb0e52f1f1d0d3f103f84ccd/packages/localize/init/index.ts#L31
The better way of translationId is:
title = $localize`:@@Home.Title:Some title text`
and you have to manually add it to your messages.xx.xlf (for example messages.fr.xlf and so on)
<trans-unit id="Home.Title"> <source>Some title text</source> <target>TRANSLATION_HERE</target> </trans-unit>
Here is some scripts which can be used to extract html + ts side localizations to xlf file. So you use $localize like @Cyclion suggests. This solution uses Ocombe's locl cli package https://www.npmjs.com/package/@locl/cli First you need to build your project without localization.
ng build ProjectName --localize=false
Then you can extract translations from "binary js"-files using locl tool. I use 0.0.1-beta.6 -version because it doesn't generate target parts in xlf file. Those target parts will ruin merge with xlf-merge. And also ng xi18n tool doesn't generate those target parts as well so structure is consistent after merge.
npx locl extract -s='dist/ProjectName/**/*.js' -f=xlf -o='projects/ProjectName/src/locale/messages_extracted.xlf' --locale=fi
Then you can combine ng xi18n result and this result. This contains every translations from html and ts but without meta data what ng xi18n command provides from html side translations. I use xlf-merge for this.
xlf-merge ./projects/ProjectName/src/locale/messages_extracted.xlf projects/ProjectName/src/locale/messages.xlf -o projects/ProjectName/src/locale/messages.xlf
This merge command will add every missing ts side translations to end of messages.xlf-file
Here is whole script.
ng xi18n --project=ProjectName --output-path src/locale && ng build ProjectName --localize=false && npx locl extract -s='dist/ProjectName/**/*.js' -f=xlf -o='projects/ProjectName/src/locale/messages_extracted.xlf' --locale=fi && xlf-merge ./projects/ProjectName/src/locale/messages_extracted.xlf projects/ProjectName/src/locale/messages.xlf -o projects/ProjectName/src/locale/messages.xlf
And after these steps you have all translation tags in messages.xlf. Then you need to generate/translate each language files using for example xliffmerge tool.
Comments
Post a Comment