Angular 5 Pipe无法执行

时间:2018-12-04 10:52:41

标签: angular angular5

我是新手。有这样的管道:

import { Pipe, PipeTransform } from '@angular/core';
import * as _ from 'lodash';

@Pipe({ name: 'arrayToString' })
export class ArrayToStringPipe implements PipeTransform {
transform(value: any[], name: string): string {
    console.log('----');
    if (_.isEmpty(value))
        return '';

    var result = _.join(_.map(value, function(e) { return name ? e[name] : e; }), ',');
    return result;
   }
}

已将记录记录到模块文件的声明部分:

import { ArrayToStringPipe } from './pipes/arrayToString.pipe';
...
@NgModule({
imports: [
    ...
],
declarations: [
    ...
    ArrayToStringPipe
],
providers: [
],
exports: [
    ...
    ArrayToStringPipe
]
})
export class SharedModule {
}

并在其他模块中使用管道:

import { SharedModule } from '../shared/shared.module';
@NgModule({
imports: [
   ...
    SharedModule,

],
declarations: [
    ...
],
exports: [
],
entryComponents: [
   ...
],
providers: [
    ...
]
})

和html

 <div *ngSwitchCase="Tags">{{ employee[field.Name] | arrayToString}}</div>

但是,在浏览器中我看到了(控制台中没有错误):

[object Object],[object Object],[object Object]

我希望看到:     tag1,tag2,tag3。

任何想法,为什么管道不起作用?

编辑:

完整html

<div *ngIf="!(employees | isEmpty)" class="employee-list">
<table class="b-table">
                <thead>
                    <tr>
                        <th *ngFor="let field of rightGridFields" [ngClass]="{'sorted-column': filter.SortColumn === field.Name }">
                            <a *ngIf="field.Sortable" [ngClass]="{'asc': !filter.SortDescending, 'desc': filter.SortDescending}" (click)="sort(field.Name)">
                                {{field.DisplayName}}
                            </a>
                            <span *ngIf="!field.Sortable">{{ field.DisplayName }}</span>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr *ngFor="let employee of employees" (mouseover)="employee.hover = true" (mouseleave)="employee.hover = false" [ngClass]="{'selected': employee.selected,'hovered': employee.hover }">
                        <td *ngFor="let field of rightGridFields" [ngSwitch]="field.Name">
                            <div *ngSwitchCase="Tags">{{ employee[field.Name] | arrayToString}}</div>
                            <div *ngSwitchCase="Birthday">{{ (employee[field.Name] ? employee[field.Name]:'') | formatLocalDate}}</div>
                            <div *ngSwitchDefault>{{ employee[field.Name] }}</div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

编辑2: 删除* ngSwitchCase =“ Tags”后,管道开始工作。是角虫吗?

2 个答案:

答案 0 :(得分:1)

从转换函数定义中删除[](即value:any []到value:any)后尝试运行此代码

transform(value: any[], name: string): string {

希望它会起作用,因为any类型包括可能是原始,数组或对象的每种数据类型,因此无需指定any[]

答案 1 :(得分:1)

谢谢大家。我的错误很愚蠢。 解决的问题是:

<div *ngSwitchCase="'Tags'">

需要为标签传递“”。