Skip to content

Instantly share code, notes, and snippets.

@navix
Last active March 5, 2017 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navix/355a7df6dbe209899338e2073af8927c to your computer and use it in GitHub Desktop.
Save navix/355a7df6dbe209899338e2073af8927c to your computer and use it in GitHub Desktop.
Angular: get i18n phrase in the code
<app-locale i18n-phrase-key phrase-key="Phrase One"
i18n-phrase-key-2 phrase-key-2="Phrase Two"
...
>
</app-locale>
...
export class Component {
@ViewChild(LocaleComponent) locale: LocaleComponent;
...
const translatedPhrase = this.locale.t('phrase-key');
}
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-locale',
})
export class LocaleComponent {
constructor(private el: ElementRef) { }
t(key: string): string {
if (this.el.nativeElement.hasAttribute(key)) {
return this.el.nativeElement.getAttribute(key);
}
else {
throw new Error(`Locale component does not have ${key} attribute`);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment