使用管道名称/元数据在运行时调用管道

roy*_*oyB 6 angular2-pipe angular

我正在尝试构建一个动态表,我可以在运行时决定使用哪个管道(如果有的话).

我正在尝试实现类似于(简化)的东西:

export class CellModel {
     public content: any;
     public pipe: string
}
Run Code Online (Sandbox Code Playgroud)

<tbody>
     <tr *ngFor="let row of data">
         <template ngFor let-cell [ngForOf]=row>
           <td *ngIf="cell.pipe">{{cell.content | cell.pipe}}</td>
           <td *ngIf="!cell.pipe">{{cell.content}}</td>
     </tr>
</tbody>
Run Code Online (Sandbox Code Playgroud)

我知道这个例子给出了一个错误.我可以使用Reflect是某种方式还是其他一些解决方案?

Gün*_*uer 5

您无法动态应用管道.你可以做的是建立一个"元"管道,决定要做什么转换.

@Pipe({
  name: 'meta'
})
class MetaPipe implements PipeTransform {
  transform(val, pipes:any[]) {
    var result = val;
    for(var pipe of pipes) {
      result = pipe.transform(result);
    }
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后像使用它一样

<td *ngIf="cell.pipe">{{cell.content | meta:[cell.pipe]}}</td>
Run Code Online (Sandbox Code Playgroud)