2
votes

I have two components, ParentComponent and 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

The code would work if it would be the same component, the child html would be directly in the parent and #parent would be on element <gridster>.

What should I use instead of ElementRef? Or maybe another solution?

1
You should use <ng-content></ng-content> inside your parent template and @ContentChildren decorator to reference components insidePatryk Uszyński

1 Answers

1
votes

You could make the gridster-item elements available to the child component.

child.component.ts

@ViewChildren(GridsterItemComponent) gridsterItems;

parent.component.ts

@ViewChild(ChildComponent) childComponent;

doSomething() {
  this.childComponent.gridsterItems.callSomeMethod();
}