Search code examples
angular2-servicesangular2-pipe

How to use services in custom pipes in angular 2


I want to display months in years on html. My filter takes number of months as an input and it should return years.

For example: if it takes 12 as input, it should return translated value as 1 year. and if it is more than 1 year, it should 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 is :

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

I don't have a clue how to make that happen. Please help.


Solution

  • Install the translate lib and its http-loader with

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

    Follow the set up guide in the @ngx-translate docs. Then import the service:

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

    Inject 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 straight away, there's also useful ones such as stream which will give you an observable which will keep streaming the value to your subscriptions even when the language changes. Which get won't. There's more methods you can use so I'd suggest you look in the docs and learn which suits you the best.