【问题标题】:Error while inserting pipe in component of angular 2 application在 Angular 2 应用程序的组件中插入管道时出错
【发布时间】:2018-06-27 09:55:33
【问题描述】:

我正在使用 Angular 2,我必须创建搜索过滤器。所以我创建了一个带有搜索逻辑的管道并将其注入所需的组件中。 但是在注入时,我得到了错误。

这是我注入管道的代码,

import { FilterPipe} from '../filter.pipe';

@Component({
  selector: 'app-dialog',
  templateUrl: './dialog.component.html',
  pipes: [FilterPipe],
  styleUrls: ['./dialog.component.css']
})

这是一个错误,

Argument of type '{ selector: string; templateUrl: string; pipes: typeof FilterPipe[]; styleUrls: string[]; }' is not assignable to parameter of type 'Component'. Object literal may only specify known properties, and 'pipes' does not exist in type 'Component'.

请任何人,建议我如何在组件中添加管道。

【问题讨论】:

    标签: angular2-pipe


    【解决方案1】:

    您的问题是您在 pipes 装饰器中使用了错误的属性 @Component

    @Component({
      selector: 'app-dialog',
      templateUrl: './dialog.component.html',
      pipes: [FilterPipe], // This line is wrong, pipes doesn't exists
      styleUrls: ['./dialog.component.css']
    })
    

    实际上,这个错误很好地说明了这一点。

    你需要把它改成providers,像这样:

    @Component({
      selector: 'app-dialog',
      templateUrl: './dialog.component.html',
      providers: [FilterPipe],
      styleUrls: ['./dialog.component.css']
    })
    

    并将其注入组件的构造函数中,如下所示:

    constructor(private filterPipe: FilterPipe) { }
    

    创建了一个简单的StackBlitz DEMO 供您查看实际情况。

    【讨论】:

      【解决方案2】:

      你能发布完整的代码吗..导入自定义管道过滤器文件时似乎有错误.. 您必须首先在该组件的模块中导入自定义管道过滤器文件,然后必须在模块的声明中声明.. 在该组件的 module.ts 文件中

      import {AdvancedFilterPipe} from './basic-filter.pipe';
      
      //Declare pipe
      
      @NgModule({
      
          imports: [DataTableModule, HttpModule, CommonModule, FormsModule, ChartModule, RouterModule],
      
          declarations: [ DashboardComponent, AdvancedFilterPipe],
      
          exports: [ DashboardComponent ],
      
          providers: [{provide: HighchartsStatic}]
      
      })
      

      您可以查看以下文章,了解如何在 Angular 中创建和使用自定义管道。 http://musttoknow.com/create-custom-pipe-use-datatable-ngfor-angular/

      使用简单的方法..它节省了我的时间。

      【讨论】:

      • 这与管道的声明无关
      • @benshabatnoam,你能告诉我它是如何不相关的回复......他问“请任何人,建议我如何在组件中添加管道。”。请建议..谢谢
      • 您已建议将管道添加到模块的声明中,但下一步是什么?声明管道只是第一步。问题是如何在组件中使用管道。
      • @benshabatnoam.. 请检查提供的教程链接,那里解释了如何使用管道..谢谢
      • 10x @Prashant M Bhavsar,查看了您的链接,发现此链接(至于您的答案)是在组件模板中使用管道的一个很好的示例。问题是这个问题是关于“如何在组件的代码中使用管道”
      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 2016-12-12
      • 2017-02-11
      • 2017-09-02
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多