Last active
March 5, 2017 07:26
-
-
Save navix/355a7df6dbe209899338e2073af8927c to your computer and use it in GitHub Desktop.
Angular: get i18n phrase in the code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<app-locale i18n-phrase-key phrase-key="Phrase One" | |
i18n-phrase-key-2 phrase-key-2="Phrase Two" | |
... | |
> | |
</app-locale> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
export class Component { | |
@ViewChild(LocaleComponent) locale: LocaleComponent; | |
... | |
const translatedPhrase = this.locale.t('phrase-key'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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