我在Angular 4中遇到了一个问题。我有一个子页面,它的结构是:
<div tableOfContents>
<page></page>
<static-page>
<page></page>
</static-page>
<dynamic-page>
<page></page
</dynamic-page>
</div>我想收集tableOfContents指令中的所有页面组件。我尝试过@ContentChildren (Page, {descendants: true}),但它只返回<div tableOfContents>的一个直接子对象,有什么办法吗?静态页面和动态页面将在页面上动态添加/删除。@ViewChildren(Page)返回未定义
发布于 2018-03-02 20:25:42
据我所知,你只有一个选项,因为你不能查询子组件中的组件。
您可以做的是将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);
}https://stackoverflow.com/questions/49038399
复制相似问题