对象中的ngFor管道错误

时间:2016-09-27 09:00:18

标签: angular typescript

我在对象中使用管道进行* ngFor,当我在我的组件中声明管道时 - 我遇到了这个错误(VS代码) - >

[ts] Argument of type '{ selector: string; templateUrl: string; pipes: typeof ObjNgFor[]; providers: typeof TableCompone...' is not assignable to parameter of type 'ComponentMetadataType'.
  Object literal may only specify known properties, and 'pipes' does not exist in type 'ComponentMetadataType'

这是我的组成部分:

    import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';

        @Pipe({ name: 'ObjNgFor',  pure: false })
        export class ObjNgFor implements PipeTransform {
            transform(value: any, args: any[] = null): any {
                return Object.keys(value).map(key => Object.assign({ key }, value[key]));
            }
        }

        @Component({
            selector: 'tablecomponent',
            templateUrl: 'app/table.template.html',
            pipes: [ObjNgFor],
            providers: [TableComponentService]
        })
        export class TableComponent implements OnInit {

            lists: any;

            constructor(public _service: TableComponentService) {

            }

        ngOnInit() {
         this._service.getServices()
            .subscribe(lists => this.lists = lists)
            }

        }

这是我的模板*ngFor direcrive:

的一部分
 <tr *ngFor="let list of lists | ObjNgFor">
                <td>{{ list.name}}</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
 </tr>

2 个答案:

答案 0 :(得分:6)

使用最新的角度版本,您无法将pipesdirectives参数用作@Component元数据,因此请从pipes删除@Component并将其添加到模块声明中如下:

import { Component, NgModule, OnInit, Pipe, PipeTransform } from '@angular/core';
import { HttpModule } from '@angular/http';

@Pipe({ name: 'objngfor',  pure: false })
export class ObjNgFor implements PipeTransform {
  transform(value: any, args: any[] = null): any {
    return Object.keys(value).map(key => Object.assign({ key }, value[key]));
  }
}

@Component({
  selector: 'tablecomponent',
  templateUrl: 'app/table.template.html'
})
export class TableComponent implements OnInit {
  lists: any;
  constructor(public _service: TableComponentService) {}
  ngOnInit() {
    this._service.getServices().subscribe(lists => this.lists = lists)
  }
}

@NgModule({
  imports     : [HttpModule],
  declarations : [TableComponent,ObjNgFor],
  providers : [TableComponentService]
})
export class AppModule {
}

答案 1 :(得分:0)

使管道名称与管道类名称不同。

示例:

@Pipe({ name: 'objngfor',  pure: false }) 

而不是

@Pipe({    name: 'ObjNgFor',  pure: false })

并更改您的模板代码,如

<tr *ngFor="let list of lists | objngfor"> ... </tr>

希望这有帮助!!!