我试图在Angular2中构建一个列表组件,该组件从组件的用户那里获取项目,项目的列和字段的模板。所以我正在尝试使用ngTemplateOutletngOutletContext(我读过的是实验性的)。但是我无法使其正常工作。

这是一个简化的组件来演示我正在尝试做的事情:

<div *ngFor="let item of items>
  <span *ngFor="let column of columns>
    <template [ngOutletContext]="{ item: item }"
              [ngTemplateOutlet]="column.templateRef"></template>
  </span>
</div>

这是组件的用法:
<my-component [items]="cars" [columns]="carColumns">
  <template #model>{{item.model}}</template>
  <template #color>{{item.color}}</template>
  <template #gearbox>{{item.gearbox}}</template>
</my-component>

这是示例数据:
cars = [
  { model: "volvo", color: "blue", gearbox: "manual" },
  { model: "volvo", color: "yellow", gearbox: "manual" },
  { model: "ford", color: "blue", gearbox: "automatic" },
  { model: "mercedes", color: "silver", gearbox: "automatic" }
];

carColumns = [
  { templateRef: "model" },
  { templateRef: "color" },
  { templateRef: "gearbox" }
];

这是一个根据Günters评论修改代码后重现问题的人:
https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv?p=preview

最佳答案

这是您需要执行的操作:

@Component({
  selector: 'my-component',
  template: `
    <div *ngFor="let item of items">
      <span *ngFor="let column of columns">
        <template [ngTemplateOutlet]="column.ref" [ngOutletContext]="{ item: item }"></template>
      </span>
    </div>`
})
export class MyComponent {
  @Input() items: any[];
  @Input() columns: any[];
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <my-component [items]="cars" [columns]="columns">
        <template #model let-item="item">{{item?.model}}</template>
        <template #color let-item="item">{{item?.color}}</template>
      </my-component>
    </div>`
})
export class App {
  @ViewChild('model') model;
  @ViewChild('color') color;
  cars = [
      { model: "volvo", color: "blue" },
      { model: "saab", color: "yellow" },
      { model: "ford", color: "green" },
      { model: "vw", color: "orange" }
    ];

  ngAfterContentInit() {
    this.columns = [
      { ref: this.model },
      { ref: this.color ]
    ];
  }
}

Plunker

关于angular - 无法让ngTemplateOutlet工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40418598/

10-09 21:13