angular-i18n work-around for translations in code?

前端 未结 5 1321
不知归路
不知归路 2020-11-28 12:26

We have to wait until Angular 6 for angular-i18n to support translations in code for error messages and such.

For those that are using angular-i18n (instead of ngx-t

5条回答
  •  生来不讨喜
    2020-11-28 12:53

    It has been a long time since my last response and it can be simplified.

    if our .html is like

    
    
    Translation app Hola Mundo

    We have in our .ts a simple ViewChildren, a variable "yet" and a variable "translation"

      yet: boolean = false;
      translation:any={}
      @ViewChildren("t")
      set translations(values: QueryList) {
        //when yet becomes true, values.length=0
        if (values.length) {
          values.forEach(c => {
            this.translation[c.nativeElement.id]=c.nativeElement.innerHTML
          })
          //it's necesary enclosed this.yet=true in a setTime to avoid 
          //the error expresion changes After Exec
          setTimeout(()=>{
            this.yet=true;
          })
    
        }
      }
    

    then we can write some like

    alert(this.translation['message1']);
    

    Update The same idea: a component implementation you have a component

    import { Component, QueryList, AfterViewInit, ContentChildren } from '@angular/core';
    @Component({
        selector: 'ng-translation',
        template: `
        
    ` }) export class TranslationComponent implements AfterViewInit { @ContentChildren("t") translations: QueryList data: any = {} yet: boolean = false; get(text: string) { return this.data[text]; } ngAfterViewInit(): void { if (this.translations.length) { this.translations.forEach(c => { this.data[c.nativeElement.id] = c.nativeElement.innerHTML }) setTimeout(() => { this.yet = true; }) } } }

    In any other component

    
      Translation app
      Hola Mundo
    
    
    @ViewChild("translation") translation:TranslationComponent
      click()
      {
        alert(this.translation.get('message1'));
      }
    

    Example in stackblitz

提交回复
热议问题