【发布时间】:2017-10-03 16:28:51
【问题描述】:
我的目标是创建一个可以采用自定义元素并使用提供的数据对其进行迭代的组件。
这是我能想到的,它工作正常。但我不满意。我想要一些不需要将自定义元素包装在 <template> 标记中的东西。
import {Component, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'sub',
template: `
<ng-content></ng-content>
`
})
export class SubComponent {}
@Component({
selector: 'my-app',
template: `
<sub>
<template ngFor #listItem [ngForOf]="list" #i="index"> //<--don't want this tag
<div>{{listItem | json}}</div>
<p>{{i}}</p>
</template>
</sub>
`,
directives: [ SubComponent ]
})
export class AppComponent {
list = [{name: 'John', age: 26},{name: 'Kevin', age: 26}, {name:'Simmons', age:26}];
}
- 上面的代码是this plunker的编辑。
- 看到了here的建议,但很模糊。
【问题讨论】:
-
你有没有看过使用
@Input将列表传递给子组件? -
可以使用
@Input传递列表数组,但是,这并不能解决将自定义元素包装在template标记中的问题。 -
我不确定我是否理解。如果您使用
@Input,则您的sub组件中不需要ng-content -
感谢@ChristopherMoore。最终解决了问题。我在下面的回答显示了我想要实现的目标。
标签: javascript angular typescript components transclusion