robisim74 / angular-l10n Goto Github PK
View Code? Open in Web Editor NEWAngular library to translate texts, dates and numbers
License: MIT License
Angular library to translate texts, dates and numbers
License: MIT License
for the Arabic languages, different countries has different settings, we want angular2localization to trigger on different countries for the same language eg.
ar-LY -> local-ar-LY.json should be loaded and updateTranslate
ar-SA -> local-ar-SA.json should be loaded and updateTranslate
ar-SR -> local-ar-SR.json should be loaded and updateTranslate
ar-EG -> local-ar-EG.json should be loaded and updateTranslate
and so on.
BTW. the same for English language (locale-en-US.json for the united state) & (locale-en-UK.json for United Kingdom).
I use your great localization library accross multiple modules and components and setup everything in my AppModule including setting the locale/language like described [here] + setCurrentLocale()
.(https://github.com/robisim74/angular2localization/blob/master/doc/quick-start.md)
So far, so good, now my questions regarding using it:
Do i have to pollute" all my components with extends locale and so on? It seems to work without it which i would highly appreciate
If i don't have to pollute my components, there is an issue with the lang parameter of the translate pipe:
{{ 'foo' | translate }}
so that the language that has been setup on bootstrap is used. But currently the texts are not translated and i get an empty outputCan you make the lang parameter optional so that the default is beeing used? Might also be related to #45
Is there already a working solution for this?
Thanks and best regards,
Matthias
I tried to build with 'npm run build' ('npm start' does not work) your sample project with latest version (node 7.2.0 and npm 4.0.2) but I get following error. What do I wrong?
Start building...
Start TSLint
TSLint completed
Start AoT compilation
ngc -p tsconfig-build.json
Error: Metadata version mismatch for module C:/tmp/angular2localization/src/services/locale.service.ts, found version 2, expected 1
at StaticReflector.getModuleMetadata (C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\static_reflector.js:500:23)
at C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\codegen.js:122:46
at Array.forEach (native)
at extractProgramSymbols (C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\codegen.js:120:10)
at CodeGenerator.codegen (C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\codegen.js:57:29)
at codegen (C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\main.js:7:81)
at Object.main (C:\tmp\angular2localization\node_modules@angular\tsc-wrapped\src\main.js:37:16)
at Object. (C:\tmp\angular2localization\node_modules@angular\compiler-cli\src\main.js:16:9)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
Compilation failed
I wonder if there is any workaround to make the translate directive works in this HTML template:
<div class="btn-container">
<input type="submit" class="btn1" value="Login" translate />
</div>
This actually doesn't work without using the TranslatePipe
like this:
<div class="btn-container">
<input type="submit" class="btn1" value="{{'Login' | translate}}" />
</div>
This works great, but I want to keep my HTML clean because another person is working on the UI separately and we agreed to some rules between us regarding the localization to use the translate directive when possible.
I made a workaround by using <button type="submit">
element instead of <input>
, And it worked.
However this will not be acceptable if the CSS is applied to a specific element type like .input[type="submit"]
which it is in my case.
With some investigations in the source code, I think the problem comes from here:
private translate(renderNode: any, nodeValue: string, key: string): void {
this.localization.translateAsync(key, this.params).subscribe(
(value: string) => {
this.renderer.setText(renderNode, nodeValue.replace(key, value));
}
);
}
Since we cannot setText
on an input element, I suggest checking the type of the renderNode
before setting the text, and to support translating input values we might use 'setElementAttribute' function.
I am using the translation pipe in html as well as the translate method of LocalizationService.
The translation pipe is working properly. But when i use translate method in my component, it works fine when i route from another page . But when i refresh the page the translation don't work and it shows the key.
Here is my sample code for my component.
`constructor(public locale: LocaleService, public localization: LocalizationService) {
super(locale, localization);
}
getDefaultTimeRanges() {
let dStr: string = this.localization.translate('D');
}`
Here from the above code i have translate the key 'D'. But it doesnot translate when i refresh the page. Also i have tried Advanced initialization but the issue remain the same.
Please guide me if i am missing anything. Thanks in advance.
Since version 1.3.0, you can also use Html attributes to translate texts, dates and numbers.
Examples for translating messages:
<h1 translate>TITLE</h1>
If you want to use parameters:
<p [translate]="{ user: username, NoMessages: messages.length }">USER_NOTIFICATIONS</p>
Examples for localization of dates & numbers:
<p localeDate>{{ today }}</p>
<p localeDate="fullDate">{{ today }}</p>
<p localeDecimal>{{ pi }}</p>
<p localeDecimal="1.5-5">{{ pi }}</p>
<p localePercent>{{ a }}</p>
<p localePercent="1.1-1">{{ a }}</p>
<p localeCurrency>{{ value }}</p>
<p localeCurrency="1.2-2" [symbol]="true">{{ value }}</p>
If you use in the component only the HTML attributes and not the pipes, you don't need to import services and extend Locale
class.
It would be beneficial to allow translations that require some dynamic values in them to be directly used with the TranslatePipe
and TranslateService
. Looking around at what other projects offer, ng2-translation allows parameters to be used as substitutions in the translate pipe and RC6's i18n will use placeholders.
A proposed usage would be:
en.json:
{
"UserNotifications": "{{ user }}, you have {{ numMessages }} new messages"
}
HTML:
<div>{{ "UserNotifications" | translate:lang:{ user: username, numMessages: messages.length } }}</div>
Typescript:
const params = {
user: username,
numMessages: messages.length
};
const translated = this.localizationService.translate("UserNotifications", params);
Hi,
I'd like to be able to output the current locale's currency symbol, i.e. £, instead of GBP. There doesn't seem to be a way to do this with the standard service.
Currently using the following but it's messy and there must be a better solution:
{{ 0 | localecurrency:defaultLocale:currency:true:'1.2-2' | slice: 0:1 }}
Can you point me in the right direction?
Thanks
Max
hi i have a timing issue in my app with initial translation in my component (template). when changing the current language later on it works as expected.
i see one call to translate pipe that is aborted because the state of the localization service is not ready.
After this initial call there are no further calls to the translate pipe.
i subscribed to translationchange in my component and triggered an app.tick(), i debugged into changedetection and the translate is not called because lang and key did not change.
so root problem seems to be that current language is set before the providers are added!?
if i add additional code after adding a provider i can workaround the issue:
localization.addProvider('url');
(this.localization).getTranslation(language); //because this.localization.updateTranslation(language); does nothing because languagecode is the same
component.lang = "";
as a sidenote: the TranslatePipe returns "" if the localization service is not ready, i would prefere that it returns the key to be consistent with lacalizationService.translate calls
@robisim74 Very nice module!
I try to implement it in my new Ionic 2 app (rc0), and I'm facing a fondamental problem:
My app relies heavily on financial calculations and planning.
So I need to display dates and numbers in the right format according to the user country, not the user language.
Indeed, for example, a date is written differently in US than in UK:
even if the language code for these two countries are the same : "en".
Same for numbers and currencies.
So my question is: is it possible to format dates, numbers, percents and currencies localized by country instead of language?
Hi,
I'm using Angular 2.0.0,
My problem is how to set default value when key is not present in translation file, it means the friendly value (eg. "No Key in DB") can be shown if the key not found.
Thanks.
Hi, thanks for this package. When I use special characters in the resource files, the Localization service throws an invalid character exception due to the 'Actualités' => é
Any ideas how to fix this?
{
"HELLO": "Bonjour {{value}}",
"NAV_MENU_HOME": "Actualités",
"NAV_MENU_SHOP": "Boutique"
}
Error:
Localization service: SyntaxError: Invalid character
"Localization service:"
{
[functions]: ,
__proto__: { },
description: "Invalid character",
message: "Invalid character",
name: "SyntaxError",
number: -2146827274,
stack: "SyntaxError: Invalid character
at Json.parse (http://localhost:8186/libs/angular2.dev.js:390:7)
at Response.prototype.json (http://localhost:8186/libs/http.dev.js:296:9)
at Anonymous function (http://localhost:8186/libs/angular2localization.js:58:13)
at MapSubscriber.prototype._next (http://localhost:8186/libs/Rx.js:5039:9)
at Subscriber.prototype.next (http://localhost:8186/libs/Rx.js:10667:9)
at onLoad (http://localhost:8186/libs/http.dev.js:672:13)
at ZoneDelegate.prototype.invokeTask (http://localhost:8186/libs/angular2-polyfills.js:380:18)
at onInvokeTask (http://localhost:8186/libs/angular2.dev.js:2177:15)
at ZoneDelegate.prototype.invokeTask (http://localhost:8186/libs/angular2-polyfills.js:380:18)
at Zone.prototype.runTask (http://localhost:8186/libs/angular2-polyfills.js:282:22)"
}
greetings Damien
Hi,
i followed the setup guide , i am using webpack , when i run the server i get
GET http://localhost:8080/assets/locale-en.json 404 (Not Found)
``
this.localization.translationProvider('../../../assets/locale-'); // Required: initializes the translation provider with the given path prefix.
is there any thing i have to add to webpack config file to let it work ?
Only on Travis, not locally.
Right now, we have sub-components that essentially have their own translation files (using .addProvider). However, when these components are loaded dynamically (via routing), the translation file never gets added. Calling updateTranslation does nothing since the language is still the same.
Any help or suggestions would be appreciated!
Another version just arrived. Can this get updated to RC6?
I'm updating to Angular 2 rc5 and I have runtime problems with the Locale service at start up.
Any ideas?
https://github.com/damienbod/Angular2LocalizationAspNetCore/tree/updatAngularRc5
Greetings Damien
Ciao di nuovo,
I'm playing with your library and I've noticed that addTranslation/translationProvider will overwrite the translationData object in LocalizationService instead of adding the new translations.
More details:
I have a SharedModule that exports a singleton LocalizationService in the forRoot method (as explained in the angular documentation) because this SharedModule is also imported by my lazy loaded module, which I'll call BModule.
In the constructor of BModule (and not in the constructor of the main component in BModule, since there's no single entry point but depends on the route!) I wrote this:
export default class BModule { constructor(_localizationService: LocalizationService) { //_localizationService.translationProvider("/app/ehr/resources/"); _localizationService.addTranslation("it", { "SET_STATUS": "Imposta stato a:" }); _localizationService.updateTranslation(); } }
and after the addTranslation/translationProvider calls the translationData object is overwritten. I don't want this because I want to keep global translations (generic things like save, cancel, ecc...) in the "core module" of my webapp, and load the translations specific for BModule and its components afterwards.
Therefore, coupling this behavior with namespaced keys (see my other Issue) I can write, in the template of a component in the BModule, something like:
`
Memory usage will still be optimized: BModule resources will be loaded ONLY if the user navigates to a proper route, otherwise not!
I have an application with many modules (some lazy-loaded) and a ton of components..
When the user change the language of the application using a menu, not all the translation are updated.
For the translations I use a mix of pipe and directive depending on where I need to put the texts.
All my components extend the Locale class as described in the documentation.
At first glance, it seems that the texts translated using the pipe are the only texts affected by the issue. And I think that the issue appears only on components with the OnPush change detection strategy.
So, for the moment, my work around for this issue is to force a reload of the whole application using location.reload()
.
Here is a link to a video showing the issue: https://drive.google.com/open?id=0B0duWwBStbRAemI1V1lPaXlkYTA
I added in the README file a table for comparison of the main solutions for Angular 2 i18n, hoping that it will help in selecting the most suitable solution for your application. If there are corrections to be made, or updates, please leave a reply here or make a pr. Thank you!
Not sure if this is environmental however tsc is throwing the below compile errors:
node_modules/angular2localization/src/services/localization.service.ts(206,16): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'.
Type '{}' is not assignable to type 'string'.
node_modules/angular2localization/src/services/localization.service.ts(343,16): error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable<any[]>'.
Type '{}' is not assignable to type 'any[]'.
Property 'length' is missing in type '{}'.
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.1",
"adal-angular": "^1.0.10",
"angular2localization": "^0.7.1",
"bootstrap": "^3.3.6",
"es6-module-loader": "^0.17.8",
"es6-promise": "^3.1.2",
"es6-shim": "^0.35.0",
"font-awesome": "^4.6.1",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.27",
"zone.js": "0.6.12"
}
Hi Robisim,
Could you please help me on angular 2 translate in angular cli project.i am new to angular2
I'm having a cyclic dependency error when using the advanced initialization and a custom Http provider:
Cannot instantiate cyclic dependency! ApplicationRef_: in NgModule AppModule in ./AppModule
Bellow is the providers section of the module, note that if I remove any of the two providers the application will compile and run with each of them individually. Only when I try to use both of them together the error occurs:
providers: [
{
provide: APP_INITIALIZER,
useFactory: initLocalization,
deps: [LocalizationConfig],
multi: true
},
{
provide: Http,
useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions, router: Router) => {
return new HttpInterceptor(xhrBackend, requestOptions, router);
},
deps: [XHRBackend, RequestOptions, Router]
}
]
Full error stack trace:
Unhandled Promise rejection: Provider parse errors: Cannot instantiate cyclic dependency! ApplicationRef_: in NgModule AppModule in ./AppModule ; Zone: <root> ; Task: Promise.then ; Value: Error: Provider parse errors: Cannot instantiate cyclic dependency! ApplicationRef_: in NgModule AppModule in ./AppModule Stack trace: NgModuleProviderAnalyzer</NgModuleProviderAnalyzer.prototype.parse@http://localhost:5555/node_modules/@angular/compiler/bundles/compiler.umd.js:9916:21 [<root>] NgModuleCompiler</NgModuleCompiler.prototype.compile@http://localhost:5555/node_modules/@angular/compiler/bundles/compiler.umd.js:18498:11 [<root>] JitCompiler</JitCompiler.prototype._compileModule@http://localhost:5555/node_modules/@angular/compiler/bundles/compiler.umd.js:26572:52 [<root>] JitCompiler</JitCompiler.prototype._compileModuleAndComponents/createResult@http://localhost:5555/node_modules/@angular/compiler/bundles/compiler.umd.js:26514:22 [<root>] Zone.prototype.run@http://localhost:5555/node_modules/zone.js/dist/zone.js?1482335873252:113:24 [<root> => <root>] scheduleResolveOrReject/<@http://localhost:5555/node_modules/zone.js/dist/zone.js?1482335873252:520:52 [<root>] Zone.prototype.runTask@http://localhost:5555/node_modules/zone.js/dist/zone.js?1482335873252:151:28 [<root> => <root>] drainMicroTaskQueue@http://localhost:5555/node_modules/zone.js/dist/zone.js?1482335873252:418:25 [<root>] ZoneTask/this.invoke@http://localhost:5555/node_modules/zone.js/dist/zone.js?1482335873252:349:25 [<root>]
Angular executes an impure pipe during every component change detection cycle. An impure pipe will be called a lot, as often as every keystroke or mouse-move.
With that concern in mind, we must implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.
From Angular Docs: https://angular.io/docs/ts/latest/guide/pipes.html
With that concern in mind, some months ago, I turned the impure pipes used for translation into pure pipes, demanding some sacrifice to those who were using this library in terms of code written and working understanding.
If you want to take away the whim, debug impure pipes (even adding a console.log at the beginning of the transform
method), and see how many times they are invoked by Angular Change Detection mechanism: even hundreds of times each time the user does something.
Using pure pipes, this happens only once: when the input parameters change (in our case the language).
Only at the bootstrap of the app this happens twice, because the view is rendered before the loading of the translation file is completed.
To overcome this, inspired by this question, I have implemented an example of advanced initialization, which doesn't render the app until the loading of translation file has been completed.
In this way, also at the bootstrap of the app, an unnecessary call doesn't occur to the pure pipes.
See quick-start that explains how to load the translation file before the app is rendered.
If you have any suggestions on how to improve this initialization, you are welcome.
RS
Hi, I am wondering if I did something wrong or it was implemented like this:
when I want to change the locale by selector/button. Only those labels/messages in the components which extends Locale will change, labels in other components still keeps the original localization.
Hi Roberto
I updated to version 0.7.1, and the localization no longer works. Empty strings are returned from the pipe.
https://github.com/damienbod/Angular2LocalizationAspNetCore/tree/angularLocalization071
Greetings Damien
Because it's just Angular, I renamed the library (Angular localization is already taken by an AngularJS library...), and because only a new name is useless, I made a code refactoring, with a lot of breaking changes.
This project started only with one injectable class for translation at the beginning of Angular 2 (it was its name), and it has grown to become heavy, but I think that clean code is important to manage the project.
I also tried to make it more beautiful and simple to use, and especially to optimize performance and size (thinking about tree shaking), so that you can only import the modules and classes that are used.
All the documentation is updated.
Greetings,
Roberto
Hi Team,
I'm unit testing a component, while the test case is running fine, I could not show labels for the text fields.
Issue : The component's HTML file contain labels for text fields with 'translate:lang' pipe, however, it is not able to pick keys from locale files while unit testing.
Below is my code :
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule, ValidatorsModule, ReactiveFormsModule, LocaleModule, LocalizationModule.forChild(),
Ng2Bs3ModalModule, UserManagementModule, HttpModule],
declarations: [TestComponent],
providers: [
MockUserService,
LocaleService,
LocalizationService,
{ provide: HttpService, useClass: MockHttpService },
{ provide: UserService, useClass: MockUserService },
SpinnerService,
CustomNotificationService,
NotificationsService,
{
provide: Router, useClass: RouterStub
},
MockBackend,
BaseRequestOptions,
EventsService,
{
provide:
Http,
useFactory: (backend: any, defaultOptions: any) => {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
}
]
}).overrideComponent(CreateUserComponent, {
set: {
templateUrl: 'create-user.component.spec.html',
providers: [
{ provide: UserService, useClass: MockUserService }
]
}
});
TestBed.compileComponents();
console.log('Test bed for create user spec created');
}));
fit('should create user',
async(inject([UserService, LocaleService, LocalizationService],
(mockUserService: UserService, locale: LocaleService, localization: LocalizationService) => {
TestBed
.compileComponents()
.then(() => {
let fixture = TestBed.createComponent(TestComponent);
let createUserInstance = fixture.debugElement.children[0].componentInstance;
let user: User = new User(0, 'user', 'created', 'successfully', 'admin', true, 'Test@123', 'Test@123', '');
let spy: jasmine.Spy = spyOn(createUserInstance, 'createUser');
createUserInstance.setModel(user);
createUserInstance.createUser();
expect(spy.calls.any()).toBe(true, 'into create user function of create user component success');
fixture.whenStable().then(() => {
fixture.detectChanges();
let de: DebugElement[] = fixture.debugElement.queryAll(By.css('input'));
expect(de.length).toBe(6);
});
});
})));
@Component({
selector: 'test-cmp',
template: '<create-user></create-user>'
})
class TestComponent extends Locale {
constructor(public locale: LocaleService, public localization: LocalizationService) {
super(null, localization);
this.locale.addLanguage('en');
this.locale.addLanguage('ru');
// Required: default language
this.locale.definePreferredLocale('en', 'US', 30);
// Required: initializes the translation provider with the given path prefix.
this.localization.translationProvider('../../translations/locale-');
// Need to update the translation.
this.localization.updateTranslation();
this.locale.setCurrentLocale('en', 'US');
}
}
Above is the code that shows following points :
let createUserInstance = fixture.debugElement.children[0].componentInstance;
, it goes to component's constructor where localeservice and localizationService objects are referenced.Please help, this is urgent.
Hello,
I get an error when i want to build my anuglar 2.1.0 project:
ERROR in app.js from UglifyJs
SyntaxError: Unexpected token: punc ({) [./~/angular2localization/angular2localization.js:2,0]
I use the latest version of angular2localization 1.1.1
I build my project like it's described in the official angular2 guide -> https://angular.io/docs/ts/latest/guide/webpack.html
Hi,
I'm using Angular 2.0.1 with Router 3.0.1
My problem is that i have a login page where i translate the text to english or german. In html my text is being translated:
<label>{{'language' | translate:lang}}:</label>
This works fine for me.
But now i'm trying to translate my text in ngOnInit
like:
ngOnInit()
{
this.languages.push({
value: 'default',
caption: this.localization.translate('default')
},
{
value: 'de',
caption: this.localization.translate('german')
},
{
value: 'en',
caption: this.localization.translate('english')
});
this.localization.updateTranslation();
}
Now im calling the Component directly by url
localhost:4200/login
and my text won't be updated. If i navigate through router (on response of a rest-call), it works fine.
Thanks
If you try to set the default like:
this.locale.definePreferredLocale('it', 'IT', 30);
it doesnt work.
Stepping through, before that method is called the defaults are empty. After, it is always set to 'en-US' regardless. This happens in demo repo itself.
Hello Roberto,
It seems that there is an issue with angular2localization if you are using it with with multiple modules and lazy loading.
Somehow the texts are not always translated and you also do not see the i18n "key", especially in internet explorer / edge.
Here is also a small video (Foobar is the translated text):
I have created a demo project (https://github.com/matthiasscudlik/angular2localization-issue) with some more explanation in the README.md so that you can reproduce it. Just run ng-serve and go to http://localhost:4200/#shared
Did i do something wrong or is it a bug? For me it seems to be an issue of the service instance management across modules.
Thanks a lot for providing this great library and best regards,
Matthias
It would make it easy when using localized data from a server api.
If you want to implement this feature, I could also implement this as a pull request.
What do you think?
Greetings Damien
As already asked to ng2-translate
project
i just would like to know if your library could support translation calling object methods.
So thanks.
I would like to use validateLocaleNumber
validation for a form field that is optional. That means both empty string or correctly formatted number are valid values.
Currently, an empty string does not pass the validation resulting into an invalid field. Is there any workaround to validate non-required inputs?
Ciao Roberto,
really good job, I like your library a lot! I was trying to understand which is better: this or ng2-translate, and I decided I'll give this a try, especially because I like the api more and your pipes are pure, and although I'm just starting with a new project, I know it'll become big, with a lot of translations in page. I can't assess the impact of impure pipes, but if the angular team itself discourages their use... :)
Anyway, I seem to understand that your library doesn't support namespaced keys like ng2-translate does e.g.:
{
"HOME": {
"TITLE": "Homepage",
"FOOTER": "Text in the footer"
},
"HELP": {
"TITLE": "Help page
}
}
I think it would be very useful to implement. Medium to big projects will certainly be split into multiple components which will need the same key, but with a namespace (like "TITLE", many components might use this key). Ofc we could use a prefix but we'd lose the nesting in the json file.
What do you think?
Once again good job, and kind regards.
Andrea
Update to rc5?
So I'm trying to make the translation to work globally, but I don't seem to get how it works. It might be my lack of understanding of how modules/services in Angular 2 work. Following the guide here I have the following setup right now:
bootstrap: [AppComponent],
declarations: [
AppComponent,
HomeComponent
],
imports: [
LocaleModule.forRoot(), // New instance of LocaleService.
LocalizationModule.forRoot(), // New instance of LocalizationService.
CoreModule,
CoursesModule
....
],
})
export class AppModule {}
And my AppComponent:
@Component({
selector: 'app',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./app.component.scss'],
templateUrl: './app.component.html'
})
export class AppComponent extends Locale implements OnInit {
constructor(
public appState: AppState,
public locale: LocaleService,
public localization: LocalizationService
) {
super(locale, localization);
this.locale.addLanguages(['en', 'es']);
this.locale.definePreferredLocale('en', 'US', 30);
this.locale.definePreferredCurrency('USD');
this.localization.translationProvider('/locale/locale-');
this.localization.updateTranslation();
}
}
And then in my CoursesComponent, I have set it as the guide for Lazy routing:
@NgModule({
imports: [
...
LocaleModule, // LocaleService is singleton.
LocalizationModule.forChild() // New instance of LocalizationService.
],
declarations: [CoursesComponent]
})
The translation works in my HomeComponent, but not in my CoursesComponent. What's weird is that if I import LocalizationModule only and not LocalizationModule.forChild(), translation works. Does that mean that it is creating an instance for the first time and the instance created from AppModule is not injected inside CoursesModule? Do I need to export the service through the CoreModule? I'm confused, any help is appreciated!
Hi,
Project :
https://drive.google.com/open?id=0B_AFMME1kY1oRWFNcXp2WkFsbDQ
The project uses angular cli , to run -> npm install , ng serve
The problem occur when the page loads , and when try to change the language
I followed the package install , and i can find any thing that may cause it
More details
localization.service.js:486 Localization service: SyntaxError: Unexpected token < in JSON at position 0(…)(anonymous function) @ localization.service.js:486SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.error @ Subscriber.js:184Subscriber._error @ Subscriber.js:128Subscriber.error @ Subscriber.js:102MapSubscriber._next @ map.js:80Subscriber.next @ Subscriber.js:89onLoad @ xhr_backend.js:67ZoneDelegate.invokeTask @ zone.js:265onInvokeTask @ ng_zone.js:227ZoneDelegate.invokeTask @ zone.js:264Zone.runTask @ zone.js:154ZoneTask.invoke @ zone.js:335
Great library and awesome documentation! I had a question about using the translate function within the component class.
Let's say I have something like this.
@Component({
...
template: '<div *ngFor="let option of sortOptions">{{option.display}}</div>'
})
export class HomeComponent extends Locale implements OnInit{
// Initializes the variable 'title' with the current translation at the time of the component loading.
public newest: string = this.localization.translate('NEWEST');
public oldest: string = this.localization.translate('OLDEST');
constructor(public localization: LocalizationService) {
this.localization.translationChanged.subscribe(
// Refreshes the variable with the new translation when the selected language changes.
() => {
this.newest = this.localization.translate('NEWEST');
this.oldest = this.localization.translate('OLDEST');
}
);
}
ngOnInit(){
this.sortOptions = [
{ display: this.newest, sortColumn: 'lastModifiedDateUtc', sortOrder: 'desc'},
{ display: this.oldest, sortColumn: 'lastModifiedDateUtc', sortOrder: 'asc'},
];
}
}
I am trying to translate the value in the sort options. It consistently returns no key even on language change. Could you give suggestions on how to make it work?
Currently, the translate pipe reads the language code from LocaleService which is fine as a default behavior
But with being the only available behavior This caused a limitation, where some areas in the view need to translate to certain language (language is already supported in the app) but no way to do so without changing the entire language in the app
We managed to add such feature in-house, with this syntax
"UserName" | translate : "ar"
But it will be much better to be supported in the library, to avoid duplicating the effort of modifying the pipe again after each new release
Hello,
I am developping an angular 2 (RC 5) application. As suggested, my components are inheriting from 'Locale' and I inject LocaleService and LocalizationService into them.
To localize strings inside .ts/.js-classes, I use
this.localization.translate('KEY_FOR_RESOURCE')
In my bootstrap component, I add a reference to my json file
this.locale.addLanguage('en');
this.locale.definePreferredLanguage('en', 5);
and I use a translation provider
this.localization.translationProvider('./resources/locale/locale-');
this.localization.updateTranslation();
All works fine in Chrome but in Internet Explorer 11 and in Edge, the keys are displayed instead of the actual resources. So I don't see the actual string but 'KEY_FOR_RESOURCE' (the parameter for the translate method).
I suspect that the Components are created before the resource file has been loaded and the LocalizationService is not yet able to provide the translations. I tried to provide them from the construtor, in ngOnInit, ngAfterViewInit and ngAfterContentInit. Nothing works.
Any ideas? Since all works fine in Chrome, I suspect there is some kind of inconsistent behavior in the asynchronous loading of the translation files.
Accessing resources from HTML works fine in all browsers, it's only .ts/.js which causes problems.
Hi,
I'm struggling with formatting a date in a md-input field. Placeholder is not working as it is in your example for digits as I need to show a text like Start Date first.
When a date is entered and I change the language (culture) the error "Invalid argument .... for pipe 'DatePipe' appears and the application stops.
Thank's in advance for your support
Hi,
I'm trying to use this library for the first time, but it seems that pipe doesnt work on my side.
I prefer to use the translate key in the HTML tag, but as i understood it, if we want to make a translation inside a HTML attribute (like value or placeholder), we must use Pipe.
For example:
<p>{{'PASSWORD' | translate}}</p>
<p translate>PASSWORD</p>
The first one doesnt work, but the second work perfectly.
I've followed the quickstart readme.
systemjs.config.js
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
'@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
'angular2localization': 'npm:angular2localization/bundles/angular2localization.umd.js'
},
AppComponent
export class AppComponent extends Locale{
constructor(public locale: LocaleService, public localization: LocalizationService) {
super(locale, localization);
this.locale.addLanguages(['fr', 'nl']);
this.locale.definePreferredLocale('fr', 'BE');
this.locale.definePreferredCurrency('EUR');
this.localization.translationProvider('./resources/locale-');
this.localization.updateTranslation();
}
// Sets a new locale & currency.
selectLocale(language: string, country: string, currency: string): void {
this.locale.setCurrentLocale(language, country);
this.locale.setCurrentCurrency(currency);
}
}
import in AppModule:
imports: [ BrowserModule, AppRoutingModule, HttpModule, FormsModule, LocaleModule.forRoot(), LocalizationModule.forRoot()],
I've made few tests but I got errors.
did someone succeed?
I'm using primeNG, and some components rely on attributes to display data, like the button:
<button pButton type="submit" label="Submit"></button>
I've tried with translate
, but it raise an Cannot read property 'nodeValue' of undefined
error. Also could be interesting to be able to translate attributes like alt
, without the need of extend from Locale
.
Hi,
I have two component, app and dashboard component. The app is home component and dashboard is normal component.
I use router like this:
{ path: 'home', component: DashboardComponent }.
I found if access localhost:8080/home, translation will be not working in dashboard component(app component is fine). I mean translation is not working when run app component and dashboard component at the same time.
Could you give me a suggestion? thanks.
If the 'key' is not present in file an undefined string is returned.
I think a good proposal is that if a If the 'key' is not present in file the same key is returned.
translate(...
...
if (value == null)
value = key;
return value;
}
Hi Roberto
I'm trying to update to the latest version, everything builds now, but nothing is rendered.
Any ideas here?
https://github.com/damienbod/Angular2LocalizationAspNetCore/tree/updatingLocalization
Greetings Damien
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.