How to use translate pipe in typescript instead of template in Angular 6

Viewed 846

I've a requirement where I need to use translate pipe of Angular inside typescript logic.

I've seen this question: How to use pipe in ts not HTML

I checked this link also: Translate your Angular App with Pipes

The answer of the above question is working but in that case the pipe was custom made. But in my case translate pipe is in-built. It changes languages for texts. My template is like this:

<my-component
  [myLabel1]="label1 | translate"
  [myLabel2]="label2 | translate"
  [myLabel3]="label3 | translate"
  [myLabel4]="label4 | translate"
  [myLabel5]="label5 | translate"
  [myLabel6]="label6 | translate">
</my-component>

To avoid so many directives I thought of creating an interface and provide all directives as one object such as:

<my-component
  [toChildAsInput]="labelObject">
</my-component>

I've created an interface: labelconfig.ts

export interface LabelConfig {
    label1: string;
    label2: string;
    label3: string;
    label4: string;
    label5: string;
    label6: string;
}

My typescript is:

import { LabelConfig } from './labelconfig';
labelObject:LabelConfig ;
ngOnInit() {
  labelObject.label1="Hello";  // how to apply pipe here
  ...
}

I'm stuck here only. How to apply same pipe inside typescript. Please help me. Is it even possible or not.

1 Answers

If you provided your pipe at the module level then simply inject it or provide it at component level in providers

providers: [ TranslatePipe ]

constructor(private translate: TranslatePipe) {}

And simple call transfom on the injected instance in component

this.data = this.translate.transform(value)
Related