Angular 2 query any element in the document from directive

1k Views Asked by At

I need to query elements in the document using querySelector since I can't provide any reference to the elements that are not in the same component as the element that the directive is being used on.

The problem is that no matter what life cycle hook I use, the directive can't find the elements with a certain class that is outside of the component that the directive it used on.

I've tried AfterContentInit and AfterViewInit but no luck.

Here's a simple example:

Component 1:

<div class="class1"></div>
<div myDirective [classesToQuery]="['class1', 'class2']"></div>

Component 2:

<div class="class2">Hero</div>

The directive:

ngAfterContentInit() {
  this.waypoint = this.getWaypointTotal();
}

queryElementsByClasses(): any[] {

  let queriedElements: any[] = [];

  for (let query of this.classesToQuery) {

    const element: any = document.querySelector('.' + query);

    if (element) {
      queriedElements.push(element);
    }
  };

  return queriedElements;
}

getWaypointTotal(): any {

  let total: number = 0;
  let elements: any[] = this.queryElementsByClasses();

  for (let element of elements) {

    const height: number = element.offsetHeight;

    total = total + height;
  };

  return total;
}
0

There are 0 best solutions below