]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/eg2/src/app/share/string/string.component.ts
LP1822414 Angular format service formatValue pipe
[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 *ngIf="template">
18         <ng-container *ngTemplateOutlet="template; context:ctx"></ng-container>
19       </ng-container>
20       <ng-container *ngIf="!template">
21         <span>{{text}}</span>
22       </ng-container>
23     </span>
24   `
25 })
26
27 export class StringComponent implements OnInit {
28
29     // Storage key for future reference by the string service
30     @Input() key: string;
31
32     // Interpolation context
33     @Input() ctx: any;
34
35     // String template to interpolate
36     @Input() template: TemplateRef<any>;
37
38     // Static text -- no interpolation performed.
39     // This supersedes 'template'
40     @Input() text: string;
41
42     constructor(private elm: ElementRef, private strings: StringService) {
43         this.elm = elm;
44         this.strings = strings;
45     }
46
47     ngOnInit() {
48         // No key means it's an unregistered (likely static) string
49         // that does not need interpolation.
50         if (this.key) {
51             this.strings.register({
52                 key: this.key,
53                 resolver: (ctx: any) => {
54                     if (this.text) {
55                         // When passed text that does not require any
56                         // interpolation, just return it as-is.
57                         return Promise.resolve(this.text);
58                     } else {
59                         // Interpolate
60                         return this.current(ctx);
61                     }
62                 }
63             });
64         }
65     }
66
67     // Apply the new context if provided, give our container a
68     // chance to update, then resolve with the current string.
69     // NOTE: talking to the native DOM element is not so great, but
70     // hopefully we can retire the String* code entirely once
71     // in-code translations are supported (Ang6?)
72     async current(ctx?: any): Promise<string> {
73         if (ctx) { this.ctx = ctx; }
74         return new Promise<string>(resolve =>
75             setTimeout(() => resolve(this.elm.nativeElement.textContent))
76         );
77     }
78 }
79