How to use services in custom channels in angular 2

I want to display months in years in html. My filter takes several months to contribute and should return years.

For example: if 12 is required as input, it should return the translated value as 1 year. and if it is more than 1 year old, it must return "2 years".

my pipe contains:

import { Pipe, PipeTransform} from '@angular/core';

@Pipe({name : 'displayMonthsInYears '})
export class DisplayMonthsInYears implements PipeTransform{
    transform(noOfMonths : number) : any {
         if(noOfMonths > 12){
            return (noOfMonths / 12 + $translate.instace('YEARS'));
         }
         return (noOfMonths / 12 + $translate.instace('YEAR'));
    }
}

      

and html:

 <div class="text-left">
     {{ contractDuration | displayMonthsInYears }}
 </div>

      

I have no clue how to do this. Please, help.

+3


source to share


1 answer


Install the translated lib and its http loader with

npm install @ngx-translate/core @ngx-translate/http-loader --save

      

Follow the setup guide in the docs@ngx-translate

. Then import the service:

import {TranslateService} from '@ngx-translate/core';

      



Insert it into your pipe and use it like this:

@Pipe({name : 'displayMonthsInYears '})

export class DisplayMonthsInYears implements PipeTransform{

  constructor(private translate: TranslateService) {}

  transform(noOfMonths : number) : any {

     if (noOfMonths > 12) {
        return (noOfMonths / 12 + this.translate.instant('YEARS'));
     }

     return (noOfMonths / 12 + this.translate.instant('YEAR'));
  }
}

      

instant

will return the value immediately, there will also be useful such as stream

, which will give you the opportunity to observe, which will maintain the streaming value for your subscribers even when changing the language. Which get

will not be. There are more methods out there that you can use, so I would suggest you look in the docs and see what works best for you.

+2


source







All Articles