Joaquín Reñé
2026-03-27 4ee50e257b32f6ec0f72907305d1f2b1212808a4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import { Http, HttpModule } from '@angular/http';
import { ModuleWithProviders, NgModule, Inject, TypeProvider, Injectable, Directive, ElementRef, Renderer } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
declare var navigator:any;
// Use as reference: https://github.com/ngx-translate/core/tree/master/src
@Injectable()
export class LocaleService {
    get URL_TPL() {return  'src/lang/messages_{0}.json'};
    
   private _devLang : string = 'en';
   private _currentLang : string = null;
    private _messages : any = null;
    private _elements = new Array<ElementRef>();
    constructor(private http: Http, @Inject('INITIAL_LANG') initLang: string) {
        var initLang = 'en';
       this.lang = initLang || this.getBrowserLang();
    }
    
    get lang() : string {
        return this._currentLang;
    }
    set lang(newLang: string) {
        this._currentLang = newLang;
        this.http.get(this._format(this.URL_TPL, newLang)).subscribe((data) => {
            this._messages = data.json();
            this.reloadTexts();
        }); 
    }
    
    isLoaded() : boolean {
        return !!this._messages
    }
    
    getBrowserLang() : string {
        var l;
        if (!navigator) return 'en';
        
        if (navigator.languages && navigator.languages.length) {
            l = navigator.languages[0];
        } else {
            l = navigator.language || 'en';
        }
        l = l.replace(/-.*/gi, '');
        if (l !== 'en' && l !== 'es')
            return 'en';        
        return l;
    }
    /**
     * It works similar to MessageFormat in Java
     */
    _format(str: string, ...params: string[]) {
        var ocur = 0;
        return str.replace(/\{(\d*)\}/g, function(match, index) {
            var idx = index === '' ? ocur : +index;
            ocur += 1;
            return params[idx];
        });
    };
    reloadTexts() : void {
        this._elements.forEach((ele: ElementRef) => {
           
            var txt = ele.nativeElement.getAttribute('i18n');
            if (!!txt) {
                ele.nativeElement.textContent = this.get(txt);
           }
        })
    }
    
    add(ele: ElementRef) {
        this._elements.push(ele);
    }
    
    /**
     * It accepts direct messages and templates:
     * {
     *  "hello": "hola",
     *  "Hello {0}!!: "Hola {0}!!"
     *  }
     * $L.get('hello'); // This returns "hola"
     * $L.get('Hello {0}!!', 'John'); // This returns: "Hola John!!" if language is spanish
     */
    get(msg: string, ...params: any[] ) : string {
        if (msg == null) {
            return '';
        }
        msg = msg.trim();
        var trans_msg = msg;
        
        if (this.isLoaded()) {
            if (this._messages[msg]) {
                trans_msg = this._messages[msg];
            } else if (this._messages[msg.toLowerCase()]) {
                trans_msg = this._messages[msg.toLowerCase()];
            } else { 
                (this._currentLang !== this._devLang) && console.error("Missing i18 key: " + msg);
                trans_msg = msg;
            }
        }
        // Enviar evento cuando el idioma cambia al $rootScope
        
        if (params.length === 0) return trans_msg;
        return this._format(trans_msg, ...params);
    }
    
}
@Directive({ selector: '[i18n]' })
export class I18nDirective {
    constructor(private el: ElementRef, private renderer: Renderer, private $L: LocaleService) {
    }
   ngAfterViewChecked() {
        var txt = this.el.nativeElement.getAttribute('i18n') || this.el.nativeElement.textContent;
        this.renderer.setElementProperty(this.el.nativeElement, 'i18n', txt.trim());
        this.$L.add(this.el);
        this.renderer.setElementProperty(this.el.nativeElement, 'innerHTML', this.$L.get(txt));
    }
}
declare global {
    interface String {
        capitalize(): string;
        cap(): string;
    }
}
String.prototype.capitalize = function() {
    return this[0].toUpperCase() + this.slice(1);
}
String.prototype.cap = String.prototype.capitalize; 
@NgModule({
    providers: [ ]
})
export class LocaleServiceModule {
    static withConfig(initLang?: string): ModuleWithProviders {
        return {
            ngModule: LocaleServiceModule,
            providers: [ 
                { provide: 'INITIAL_LANG', useValue: initLang },
                LocaleService
            ]
        }
    }
}