我想访问ng-content的内容,一开始只是为了获得内容元素的数量,但稍后会有更多精彩的内容。
例如:
@Component({
selector: 'my-container',
template: `
<div class="my-container">
<div class="my-container-nav"><a class="my-container-previous"></a></div>
<div class="my-container-body">
<div class="my-container-items">
<ng-content></ng-content>
</div>
</div>
<div class="my-container-nav"><a class="my-container-next"></a></div>
</div>
`
})
export class MyContainer implements AfterContentInit {
@ContentChildren(???) containerItems : QueryList<???>;
ngAfterContentInit() {
console.log('after content init: ' + this.containerItems.length);
}
}我应该将什么类型作为content子项的类型?
它们可能是任何东西。我尝试了ElementRef,但这不起作用,总是给出一个零的计数。
使用示例:
<my-container>
<div>some content here</div>
<another-component [title]="'another component there'"></another-component>
<div>there's lots of content everywhere</div>
<span>no assumptions would be fair</span>
</my-container>我希望看到“after content init: 4”。
发布于 2016-07-16 20:12:48
我误解了@ContentChildren。它并不代表所有内容。它表示ng-content中的@Components。
要直接回答这个问题:
如果我事先不知道@Components的类型,我将如何在ng-content中获取@Components,目前还不清楚。但我现在意识到这有点傻:如果我不知道它们是什么,我到底想用它们做什么?
间接回答这个问题:
要访问ng-content的所有内容,我可以在ng-content的父类中引入一个模板变量(#items),并通过@ViewChild将其作为elementRef引用。然后,可以这样计算孩子的数量:
@Component({
selector: 'my-container',
template: `
<div class="my-container">
<div class="my-container-nav"><a class="my-container-previous"></a></div>
<div class="my-container-body">
<div #items class="my-container-items">
<ng-content></ng-content>
</div>
</div>
<div class="my-container-nav"><a class="my-container-next"></a></div>
</div>
`
})
export class MyContainer implements OnInit {
@ViewChild('items') items: ElementRef;
ngOnInit() {
console.log('count is: ' + this.items.nativeElement.children.length);
}
}对于其他面临类似困惑的人,我可以在@ContentChildren上进行更多的扩展。假设我有两个@Components: component-a和component-b,我知道消费者会将这两个放在我的组件的内容中:
<my-component>
<component-a></component-a>
<div>random html</div>
<component-b></component-b>
<component-a></component-a>
</my-component>然后,在my-component中,我可以获取对各个组件类型的所有实例的引用:
export class MyContainer implements AfterContentInit {
@ContentChildren(ComponentA) componentAInstances: QueryList<ComponentA>;
@ContentChildren(ComponentB) componentBInstances: QueryList<ComponentB>;
ngAfterContentInit() {
console.log('count of component A: ' + this.componentAInstances.length);
console.log('count of component B: ' + this.componentBInstances.length);
}
}控制台将显示有2个组件A和1个组件B。
我应该指出的是,这是在候选版本4中。
https://stackoverflow.com/questions/38408912
复制相似问题