As of today in Angular 6 i18n is only available in the templates. So what if we want to use translated messages programatically and outside templates?
I still use the component template html file to declare the message to be translated, but by obtaining the TemplateRef ViewChild in the component typescript file I can get the translated messages from typescript.
<ng-template #boardInvitationEmailBody let-organization="organization" let-url="url">
<ng-container i18n>You have been invited to join the board portal for</ng-container>
{{organization}}.
<ng-container i18n>
Please follow the link to:
</ng-container>
{{url}}
</ng-template>
So in the typescript code i can now call the createEmailBodyTranlated text method to get the translated text for use outside the template.
@ViewChild('boardInvitationEmailBody') boardInvitationEmailBody: TemplateRef;
createEmailBodyTranslatedText(organization: string, url: string): string{
const bodyviewref = emailbodytemplateref.createEmbeddedView({
organization: organization,
url: url
});
bodyviewref.detach();
bodyviewref.detectChanges();
return bodyviewref.rootNodes.map(node => node.textContent).join('');
}
Comments