How to use a pipe in a component in Angular 2?

后端 未结 4 1272
终归单人心
终归单人心 2021-01-12 05:22

I have a pipe class which returns data based on the arguments you are passing. I know how to use it in my template HTML using the | symbol, but I want to use it

4条回答
  •  -上瘾入骨i
    2021-01-12 05:43

    I give solutions to solve this question from previous answers:

    • First solution from @Eran Shabi answer:

    You can create instance from Pipe class then use it's transform method within component class, Like this

    @Component({
      ...
    })
    export class Component {
    
      method() {
        const date: sting = '24-05-2020';
    
        const datePipe = new DatePipe();
        const formatedDate = datePipe.transform(date, 'shortTime');
      }
    }
    
    • Second solution from @Alexander Leonov answer:

    You can Provide DatePipe using @component Tag Or Using @Module tag under your Module class for this Component Then using Dependency injection to inject DatePipe instance into Component's constructor, Like this

    @Component({
      ...
      providers: [DatePipe] // if you want to provide DatePipe under Module see @Alexander Leonov answer
    })
    export class Component {
    
      Component(private _datePipe: DatePipe) {
      }
    
      method() {
        const date: sting = '24-05-2020';
    
        const formatedDate = this._datePipe.transform(date, 'shortTime');
      }
    }
    

    Notices:

    • Like Built-in Pipes classes, also your custom Pipe can apply this solutions

    • This Solutions apply on Angular v7+, I Don't known is work with Angular v2

提交回复
热议问题