Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(service): allow setting translations in deep objects #1382

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion projects/ngx-translate/core/src/lib/translate.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,15 @@ export class TranslateService {
* Sets the translated value of a key, after compiling it
*/
public set(key: string, value: string, lang: string = this.currentLang): void {
this.translations[lang][key] = this.compiler.compile(value, lang);
const keys = key.split('.');
const translationKey = keys.pop() as string;
const translation = keys.reduce((translation, subKey) => {
if (!translation[subKey] || typeof translation[subKey] !== 'object') {
translation[subKey] = {};
}
return translation[subKey];
} , this.translations[lang]);
translation[translationKey] = this.compiler.compile(value, lang);
this.updateLangs();
this.onTranslationChange.emit({lang: lang, translations: this.translations[lang]});
}
Expand Down
15 changes: 15 additions & 0 deletions projects/ngx-translate/core/tests/translate.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,21 @@ describe('TranslateService', () => {
translate.set("TEST", "This is a test", 'en');
});

it('should set a nested property in the translation value', () => {
const translation = { name: 'Name' } as any;
const defaultLang = 'en';
translate.setTranslation(defaultLang, translation);
translate.set('profile.name', 'Profile Name', defaultLang);
expect(translation?.profile?.name).toEqual('Profile Name');
});

it('should replace an existing translation ', () => {
const translation = { name: 'OldName' } as any;
translate.setTranslation('en', translation);
translate.set('name', 'New Name', 'en');
expect(translation.name).toEqual('New Name');
});

it('should trigger an event when the lang changes', () => {
let tr = {"TEST": "This is a test"};
translate.setTranslation('en', tr);
Expand Down