]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/string/string.component.ts
LP#1775466 Angular(6) base application
[Evergreen.git] / Open-ILS / src / eg2 / src / app / share / string / string.component.ts
1 /*j
2  * <eg-string #helloStr text="Hello, {{name}}" i18n-text></eg-string>
3  *
4  * import {StringComponent} from '@eg/share/string.component';
5  * @ViewChild('helloStr') private helloStr: StringComponent;
6  * ...
7  * this.helloStr.currrent().then(s => console.log(s));
8  *
9  */
10 import {Component, Input, OnInit, ElementRef, TemplateRef} from '@angular/core';
11 import {StringService} from '@eg/share/string/string.service';
12
13 @Component({
14   selector: 'eg-string',
15   template: `
16     <span style='display:none'>
17     <ng-container *ngTemplateOutlet="template; context:ctx"></ng-container>
18     </span>
19   `
20 })
21
22 export class StringComponent implements OnInit {
23
24     // Storage key for future reference by the string service
25     @Input() key: string;
26
27     // Interpolation context
28     @Input() ctx: any;
29
30     // String template to interpolate
31     @Input() template: TemplateRef<any>;
32
33     // Static text -- no interpolation performed.
34     // This supersedes 'template'
35     @Input() text: string;
36
37     constructor(private elm: ElementRef, private strings: StringService) {
38         this.elm = elm;
39         this.strings = strings;
40     }
41
42     ngOnInit() {
43         // No key means it's an unregistered (likely static) string
44         // that does not need interpolation.
45         if (this.key) {
46             this.strings.register({
47                 key: this.key,
48                 resolver: (ctx: any) => {
49                     if (this.text) {
50                         // When passed text that does not require any
51                         // interpolation, just return it as-is.
52                         return Promise.resolve(this.text);
53                     } else {
54                         // Interpolate
55                         return this.current(ctx);
56                     }
57                 }
58             });
59         }
60     }
61
62     // Apply the new context if provided, give our container a
63     // chance to update, then resolve with the current string.
64     // NOTE: talking to the native DOM element is not so great, but
65     // hopefully we can retire the String* code entirely once
66     // in-code translations are supported (Ang6?)
67     current(ctx?: any): Promise<string> {
68         if (ctx) { this.ctx = ctx; }
69         return new Promise(resolve => {
70             setTimeout(() => resolve(this.elm.nativeElement.textContent));
71         });
72     }
73 }
74