Can't get ngTemplateOutlet to work
我试图在Angular2中构建一个列表组件,该组件从组件的用户那里获取项目,项目的列和字段的模板。 所以我正在尝试使用
这是一个简化的组件来演示我正在尝试做的事情:
1 2 3 4 | <span *ngFor="let column of columns> <template [ngOutletContext]="{ item: item }" [ngTemplateOutlet]="column.templateRef"></template> </span> |
这是组件的用法:
1 2 3 4 5 | <my-component [items]="cars" [columns]="carColumns"> <template #model>{{item.model}}</template> <template #color>{{item.color}}</template> <template #gearbox>{{item.gearbox}}</template> </my-component> |
这是示例数据:
1 2 3 4 5 6 7 8 9 10 11 12 | 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
这是您需要执行的操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | @Component({ selector: 'my-component', template: ` <span *ngFor="let column of columns"> <template [ngTemplateOutlet]="column.ref" [ngOutletContext]="{ item: item }"></template> </span> ` }) export class MyComponent { @Input() items: any[]; @Input() columns: any[]; } @Component({ selector: 'my-app', template: ` <my-component [items]="cars" [columns]="columns"> <template #model let-item="item">{{item?.model}}</template> <template #color let-item="item">{{item?.color}}</template> </my-component> ` }) 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 ] ]; } } |
柱塞
更新Angular 5
另请参见https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29
原版的
请勿同时使用
如果要传递对象,请不要使用
它应该是
1 | [ngTemplateOutlet]="column.templateRef" |
柱塞示例
您可以在没有ngOutletContext的情况下进行操作。 您必须使用ng-template而不是template。
以下代码对我有用:
app.component.html:
1 2 3 4 | <ng-template #c1> </app-child1> </ng-template> </app-parent> |
app-parent是app-component的子代。 app-child在app-component中声明为模板,此模板在app-parent中使用。
app.parent.html:
1 2 3 4 5 | <p> <ng-template [ngTemplateOutlet]="templateChild1"></ng-template> </p> |
app.parent.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Component({ selector: 'app-parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.css'] }) export class ParentComponent implements OnInit { @Input() public templateChild1: TemplateRef; public ngOnInit() { } } |