Is it possible to equalize non-siblings elements height within same component using directive?

Viewed 17

<app-comp>
  <div class="box">
    <div class="appleA" equalizeHeight [equal-height-id]="'a1'"></div>
  </div>
  <div class="box">
    <div class="appleB" equalizeHeight [equal-height-id]="'a1'"></div>
  </div>
</app-comp>

Here I am trying to make a directive, which is called 'equalizeHeight', and I hope it will work like :

"If there is another element(within same component) that has 'equalizeHeight' directive and with same input 'equal-height-id' value, then equalize their height."

Is it possible?

I tried but got stuck on how to access another element (which has same directive on it) :(

1 Answers

Is it possible?

Definitely possible. Though definitely far from optimal. I think you probably should re-think either the design, or why this can't be achieved using css to make absolutely sure that you actually NEED to handle it this way.

You should also restraint yourself from using measurement methods that can cause reflow. Which I think leaves you with using IntersectionObservers - though there might be other solutions as well.

Note that even without causing reflows due to measuring, this can get dirty especially if you have a lots of elements connected with one "id", unless you find a way to synchronize to resizing of the elements so that they occur in a single frame (e.g. using something along the lines of requestAnimationFrame()).

I tried but got stuck on how to access another element (which has same directive on it) :(

You probably want a service that's injected into the directive, but provided on either module level or component level (depending on your needs). The service would be responsible for storing the measurements for different ids and emitting changes if a new measurement is added. The directive would subscribe to changes of measurements stored in the service and resize the underlying element accordingly.

Related