我有以下内容:
main.module.ts
//Importing "my_section"
...
import { my_section } from './my_section';
@NgModule({
declarations: [...],
imports: [..., my_section],
exports: [...]
})
export class main_pageModule {}
main.html中
//As an example, let say I have three "my_section"
<div class="top">
<my_section></my_section>
<my_section></my_section>
<my_section></my_section>
</div>
然后,
my_section.ts
...
@Component({
selector: 'my_section',
templateUrl: 'my_section.html'
})
export class my_section{
...
}
这是它的简化版本:如您所见,<my_section></my_section>
已从my_section.ts
导入main.module.ts
。
我正试图在每个<my_section></my_section>
进入视图时触发一个函数。
我尝试使用ViewChild
,但没有运气。
我知道如何检测自定义元素何时出现?
谢谢!
答案 0 :(得分:1)
尝试在组件中使用ViewChildren
装饰器(不在示例中的模块中):
import { AfterViewInit, Component, QueryList, ViewChildren } from '@angular/core';
import { my_section } from './my_section';
...
class <YOUR_COMPONENT_NAME> implements AfterViewInit {
@ViewChildren(my_section) mySections: QueryList<my_section>;
ngAfterViewInit() {
// mySections are set at this stage
// you may listen to mySections change
this.mySections.changes.subscribe(section => {
// section is available
});
// or just iterate over available sections
this.mySections.forEach(section => {
// section is available
});
}
}