Lucas Possatti
Lucas Possatti

Reputation: 33

How to translate Typescript strings in a Angular 2 app?

I know of two major platforms for Angular 2 i18n: The official way, and ng2-translate. I am much more inclined to use what the official docs recommend. For me it's very clear how to translate the HTML strings. But there is one thing I didn't get yet: How do I translate the Typescript strings?

For example, I have the following component that uses the built-in i18n solution:

import { Component } from '@angular/core';

@Component({
    moduleId: module.id,
    selector: 'hello',
    template: `
        <h1 i18n>Hello {{name}}!</h1>
        <button (click)="notify()"></button>
    `
})
export class HelloComponent {

    private name = 'John Doe';

    notify() {
        /* How do I translate this? */
        alert(`Hello ${this.name}!`);
    }
}

The string placed in the HTML will be translated. But how do I translate the string shown in the alert? If there is not a native way, what would be the recommended way to accomplish this?

Upvotes: 3

Views: 3415

Answers (1)

Jim Buck
Jim Buck

Reputation: 2444

The Angular team is very focused on creating a core product with some additional services that others can optionally use (routing, translations, etc). So don't discredit any community-made libraries, that's what makes Angular so useable!

That being said, I highly recommend ng2-translate for your needs. You can preload translations, call them synchronously or asynchronously, and use it as a pipe in a template or via a service in your component classes.

Upvotes: 1

Related Questions