无法使ngTemplateOutlet工作

Ham*_*pus 23 angular

我正在尝试在Angular2中构建一个列表组件,它获取组件用户的项目字段的项目,列和模板.所以我试图使用ngTemplateOutletngOutletContext(我读过的是实验性的).但我无法让它发挥作用.

这是一个简化的组件,用于演示我要做的事情:

<div *ngFor="let item of items>
  <span *ngFor="let column of columns>
    <template [ngOutletContext]="{ item: item }" 
              [ngTemplateOutlet]="column.templateRef"></template>
  </span>
</div>
Run Code Online (Sandbox Code Playgroud)

以下是组件的用法:

<my-component [items]="cars" [columns]="carColumns">
  <template #model>{{item.model}}</template>
  <template #color>{{item.color}}</template>
  <template #gearbox>{{item.gearbox}}</template>
</my-component>
Run Code Online (Sandbox Code Playgroud)

以下是示例数据:

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" }
];
Run Code Online (Sandbox Code Playgroud)

以下是根据Günters评论调整代码后再现问题的傻瓜:https://plnkr.co/edit/jB6ueHyEKOjpFZjxpWEv p = preview

Baz*_*nga 26

这是你需要这样做的方式:

@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 ]
    ];
  }
}
Run Code Online (Sandbox Code Playgroud)

Plunker

  • 谢谢一堆.我离我不远,但远远不足以感受到将头撞在墙上的冲动. (2认同)

Gün*_*uer 15

更新Angular 5

ngOutletContext 被重命名为 ngTemplateOutletContext

另见https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

原版的

不要使用[]{{}}在一起.一个或另一个但不是两者.

{{}}如果要传递对象,请不要使用,因为{{}}用于字符串插值.

它应该是

[ngTemplateOutlet]="column.templateRef"
Run Code Online (Sandbox Code Playgroud)

Plunker的例子

  • 无论如何,谢谢你的帮助.这不是比赛. (2认同)