我在Angular 4中遇到了问题。我有一个子页面,其结构如下:
<div tableOfContents>
<page></page>
<static-page>
<page></page>
</static-page>
<dynamic-page>
<page></page
</dynamic-page>
</div>
我想收集tableOfContents指令中的所有Page组件。我试过@ContentChildren (Page, {descendants: true})
,但它只让我从<div tableOfContents>
回来了一个直接的孩子,有什么方法吗?将在页面上动态添加/删除静态页面和动态页面。 @ViewChildren(Page)
返回undefined
据我所知,您只有一个选项,因为您无法查询进入子组件的组件。
您可以做的是将page
实例存储在服务中,并从tableOfContents
指令中获取它们。
这样的事情应该足够了:
import {Injectable} from '@angular/core';
import {PageComponent} from '<path-to-page>';
@Injectable()
export class PageInstancesService {
public instances = [];
constructor() {}
}
然后在你的page
组件中你会做:
constructor(
private pis: PageInstancesService
) {}
ngOnInit() {
this.pis.instances.push({id: <some-unique-id>, instance: this});
}
推送一个新实例。要在实例销毁后删除它,您将添加ngOnDestroy
:
ngOnDestroy() {
const i = // Function to get instance index in array goes here
this.pis.instances.splice(i, 1);
}