使用管道名称/元数据

时间:2016-08-31 14:55:16

标签: angular angular2-pipe

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

我试图实现与(简体)类似的东西:

export class CellModel {
     public content: any;
     public pipe: string
}

表格

<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>

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

2 个答案:

答案 0 :(得分:5)

您无法动态应用管道。你可以做的是建立一个&#34; meta&#34;管道决定要做什么转换。

@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;
  }
}

然后像

一样使用它
<td *ngIf="cell.pipe">{{cell.content | meta:[cell.pipe]}}</td>

答案 1 :(得分:4)

For runtime compile only you can create a directive which will compile template dynamically.

UPDATE:

Using compileModuleAndAllComponentsAsync for RC.6^

dynamic-pipe.ts

  ngAfterViewInit() {
    const data = this.data.content;
    const pipe = this.data.pipe;

    @Component({
      selector: 'dynamic-comp',
      template: '{{ data | ' + pipe  + '}}'
    })
    class DynamicComponent  {
        @Input() public data: any;
    };

    @NgModule({
      imports: [BrowserModule],
      declarations: [DynamicComponent]
    })
    class DynamicModule {}

    this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
      .then(({moduleFactory, componentFactories}) => {
        const compFactory = componentFactories.find(x => x.componentType === DynamicComponent);
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        const cmpRef = this.vcRef.createComponent(compFactory, 0, injector, []);
        cmpRef.instance.data = data;
      });
  }

Plunker sample RC.6^


OBSOLETE SOLUTION

In RC.5 you can use Compiler.compileComponentSync/Async to do that:

dynamic-pipe.ts

@Directive({
  selector: 'dynamic-pipe' 
})
export class DynamicPipe {
  @Input() data: CellModel;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {}

  ngAfterViewInit() {
    const metadata = new ComponentMetadata({
      template: '{{ data | ' + this.data.pipe  + '}}'
    });

    const data = this.data.content;
    const decoratedCmp = Component(metadata)(class DynamicComponent {  data = data; });

    this.compiler.compileComponentAsync(decoratedCmp)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], 
           this.vcRef.parentInjector);
        this.vcRef.createComponent(factory, 0, injector, []);
      });
  }
}

And use it this way:

<template ngFor let-cell [ngForOf]="row">
   <td><dynamic-pipe [data]="cell"></dynamic-pipe></td>
</template>

See also the plunker sample RC.5 that demonstrates this feature.

Anyway i think Günter's solution is preferable