angular-i18n work-around for translations in code?

前端 未结 5 1313
不知归路
不知归路 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:50

    I have a "bizarro" work-around We can have two components

    app-text.component.ts

    import { Component} from '@angular/core';
    
    @Component({
      selector: 'text',
      template:``
    })
    export class AppTextComponent{}
    

    and app-translation.component.ts

    import { Component, QueryList, ElementRef, ContentChildren } from '@angular/core';
    import { AppTextComponent } from './app-text.component';
    
    @Component({
      selector: 'app-translation',
      template: ``
    })
    export class AppTranslationComponent{
      @ContentChildren(AppTextComponent, { read: ElementRef }) divs: QueryList;
      constructor() { }
    
      translate(id: string): string {
        let nativeElement: any = this.divs.find(e => e.nativeElement.id == id);
        return nativeElement ? nativeElement.nativeElement.innerText : "";
      }
    }
    

    Then, in a component we can have some like

      
        Translation app
        Hola Mundo
      
    
    //In your code you can use a ViewChild and the function "traslate"
      @ViewChild('translations') t;
    
      alert(this.t.translate("message1"));
    

提交回复
热议问题