【发布时间】:2019-09-08 18:10:39
【问题描述】:
我有两个组件,ParentComponent 和 ChildComponent:
parent.component.html
<child-selector #parent></child-selector>
parent.component.ts
@ViewChild('parent', { read: ElementRef }) parent: ElementRef<any>;
doThis(event) {
this.parent.nativeElement.childNodes.forEach(e => {
if (e.tagName === 'GRIDSTER-ITEM') {
console.log("do stuff here");
}
});
}
child.component.html
<gridster>
<grister-item></gridster-item>
<gridster>
child.component.ts
如果代码是同一个组件,则代码将起作用,子 html 将直接位于父级中,#parent 将位于元素 <gridster> 上。
我应该使用什么来代替 ElementRef? 或者也许是另一种解决方案?
【问题讨论】:
-
你应该在你的父模板中使用
<ng-content></ng-content>和@ContentChildren装饰器来引用里面的组件
标签: angular