【问题标题】:The @component in pipes not working angular2管道中的@component 不起作用 angular2
【发布时间】:2017-07-02 03:25:26
【问题描述】:

我不知道管道中的组件:

[] 错误

[错误信息] '{ selector: string; 类型的参数模板网址:字符串;管道:任何[]; }' 不可分配给“组件”类型的参数。 对象字面量只能指定已知属性,而“组件”类型中不存在“管道”。

通知列表.component.ts

import {Component, OnInit} from '@angular/core';
import {ocNotice} from './product';
import {NoticeFilterPipe} from './product-filter.pipe';
import {NoticeService} from './product.service'

@Component({
    selector : 'pm-products',
    templateUrl : './app/products/product-list.component.html',
    pipes: [ noticeFilter ]
})

export class ProductListComponent{
    pageTitle : string = 'Notice List';
    imgW : number = 30;
    imgH : number = 30;
    showImage : boolean = false;
    listFilter : string;
    notice : ocNotice[];

constructor(private _noticeService : NoticeService){

}
toggleImage() : void{
    this.showImage = !this.showImage;
}

ngOnInit() : void{
    console.log("Oninit");
    this.notice = this._noticeService.getProduct();
}

product-filter.pipe.ts

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

@Pipe({
    name : 'noticeFilter'
})

export class NoticeFilterPipe implements PipeTransform{
    transform(value : ocNotice[], args : string) : ocNotice[]{
        let filter : string = args[0] ? args[0].toLocaleLowerCase() : null;
       return filter ? value.filter((notice : ocNotice) => 
           notice.title.toLocaleLowerCase().indexOf(filter) != -1) : value;
    }
}

【问题讨论】:

  • 您以错误的方式引入管道。阅读我的回答并按照说明操作:stackoverflow.com/questions/42093552/…
  • 首先,你应该在你的.ts - component文件中声明pipe in your module. Now, if you pretend to use the pipe`,你必须把它:pipes: [ noticeFilter ]改为:providers: [ NoticeFilterPipe ]。如果你想在 template 中使用它,你只需要在你的 module. 中声明它
  • 您使用的是什么版本的 Angular 2?据我所知,pipe 不再在component 文件中声明;它必须在moduledeclaration 中声明。

标签: angular typescript


【解决方案1】:

如果您收到此错误:

'{ selector: string; 类型的参数模板网址:字符串;管道:typeof MattDamon[]; }' 不可分配给“组件”类型的参数。 对象字面量只能指定已知属性,而“组件”类型中不存在“管道”。

而不是在@component 的管道[] 数组中添加管道, 在 'app.modules.ts' 内的 'declarations' 数组中添加管道,无需使用 'pipes' 数组

【讨论】:

  • 这不是让管道在全球范围内可用,而不是仅限于想要利用它的组件吗?当过滤器是通用的并且需要在整个应用程序中可用时,我可以看到您的解决方案很好,但是我的过滤器只需要在特定组件中使用..您的方法不适合。
猜你喜欢
  • 2017-05-28
  • 2016-07-25
  • 2018-02-14
  • 2016-11-07
  • 2016-04-14
  • 2018-02-14
  • 2018-03-12
  • 2017-05-27
  • 2017-02-05
相关资源
最近更新 更多