Diz*_*zzy 27 typescript angular2-ngcontent angular
我的简化目标是构建一个包含项目模板的列表组件.例如:
<list>item</list>
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
@Component({
selector: 'list',
template: `
<ul>
<li *ngFor="let i of items" >
<ng-content></ng-content>
</li>
</ul>
`
})
class List {
items = [1, 2, 3];
}
@Component({
selector: 'app',
directives: [List],
template: '<list>item</list>'
})
class App { }
bootstrap(App, []);
Run Code Online (Sandbox Code Playgroud)
预期结果:
实际结果:
•
•
•项目
RVa*_*een 28
我就这样做了:
用法:
<template #myTemplate let-item="item">
<strong>Name: </strong> {{item.name}}<br>
<strong>Id: </strong> {{item.id}}
</template>
<app-template-param [items]="items" [template]="myTemplate"></app-template-param>
Run Code Online (Sandbox Code Playgroud)
零件:
@Component({
selector: 'app-template-param',
templateUrl: 'template-param.html'
})
export class TemplateParamComponent implements OnInit {
@Input() items: Array<any>;
@Input() template: TemplateRef<any>;
}
Run Code Online (Sandbox Code Playgroud)
组件HTML
<template #defaultTemplate let-item="item">
<strong>{{item.name}}</strong>
</template>
<ul>
<li *ngFor="let item of items">
<template [ngTemplateOutlet]="template || defaultTemplate" [ngOutletContext]="{item: item}"></template>
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
Igo*_*orL 14
我发现了3种方法
@Component({
selector: 'dynamic-list',
template: '<div *ngFor="#item of items" *ngForTemplate="itemTemplate"></div>'
})
export class DynamicListComponent {
@ContentChild(TemplateRef)
public itemTemplate: TemplateRef;
@Input()
public items: number[];
}
<dynamic-list [items]="items">
<div template="#item">
Inline template item #: {{item}}
</div>
</dynamic-list>
Run Code Online (Sandbox Code Playgroud)
输出:
Inline template item #: 1
Inline template item #: 2
Inline template item #: 3
Inline template item #: 4
Run Code Online (Sandbox Code Playgroud)
plunker:https://plnkr.co/edit/ollxzUhka77wIXrJGA9t ? p = preview
查看更多https://github.com/ilio/ng2-dynamic-components/blob/master/README.md
归档时间: |
|
查看次数: |
15568 次 |
最近记录: |