我想访问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); } }
我将什么作为内容儿童的类型?
它们可以是任何东西.我尝试过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>
我希望看到“在内容init:4之后”.
解决方法
我误解了@ContentChildren.它并不代表所有内容.它代表ng-content中的@Components.
直接回答这个问题:
如果我不提前知道他们的类型,我还不清楚如何在ng-content中获得@Components.但我现在意识到这有点傻:如果我不知道它们是什么,我认为我究竟会怎样对待它们?
间接回答这个问题:
要访问ng-content的所有内容,我可以将模板变量(#items)引入ng-content的父级,并通过@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.假设我有2个@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.