The pipe ' ' could not be found angular2 custom pipe

后端 未结 9 1048
时光说笑
时光说笑 2020-11-27 14:33

I can\'t seem to fix this error. I have a search bar and an ngFor. I am trying to filter the array using a custom pipe like this:



        
相关标签:
9条回答
  • 2020-11-27 15:01

    You need to include your pipe in module declaration:

    declarations: [ UsersPipe ],
    providers: [UsersPipe]
    
    0 讨论(0)
  • 2020-11-27 15:08
    import { Component, Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'timePipe'
    })
    export class TimeValuePipe implements PipeTransform {
    
      transform(value: any, args?: any): any {
       var hoursMinutes = value.split(/[.:]/);
      var hours = parseInt(hoursMinutes[0], 10);
      var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
      console.log('hours ', hours);
      console.log('minutes ', minutes/60);
      return (hours + minutes / 60).toFixed(2);
      }
    }
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Angular';
      order = [
        {
          "order_status": "Still at Shop",
          "order_id": "0:02"
        },
        {
          "order_status": "On the way",
          "order_id": "02:29"
        },
        {
          "order_status": "Delivered",
          "order_id": "16:14"
        },
         {
          "order_status": "Delivered",
          "order_id": "07:30"
        }
      ]
    }
    
    Invoke this module in App.Module.ts file.
    
    0 讨论(0)
  • 2020-11-27 15:11

    I found the "cross module" answer above very helpful to my situation, but would want to expand on that, as there is another wrinkle to consider. If you have a submodule, it also can't see the pipes in the parent module in my testing. For that reason also, you may need to put pipes into there own separate module.

    Here's a summary of the steps I took to address pipes not being visible in the submodule:

    1. Take pipes out of (parent) SharedModule and put into PipeModule
    2. In SharedModule, import PipeModule and export (for other parts of app dependent on SharedModule to automatically gain access to PipeModule)
    3. For Sub-SharedModule, import PipeModule, so it can gain access to PipeModule, without having to re-import SharedModule which would create a circular dependency issue, among other problems.

    Another footnote to the above "cross module" answer: when I created the PipeModule I removed the forRoot static method and imported PipeModule without that in my shared module. My basic understanding is that forRoot is useful for scenarios like singletons, which don't apply to filters necessarily.

    0 讨论(0)
提交回复
热议问题