Skip to content

Instantly share code, notes, and snippets.

@nikosanif
Created April 20, 2021 07:39
Show Gist options
  • Save nikosanif/8793befb4d7e98a4d0887fc46257d2c5 to your computer and use it in GitHub Desktop.
Save nikosanif/8793befb4d7e98a4d0887fc46257d2c5 to your computer and use it in GitHub Desktop.

The Problem

Interactive web designs require elements with dynamic height that depends on their location in the window viewport. More specifically, their height starts at the top offset position of the element inside the window and ends at the end of the window. In this article we will try to implement dynamic height using Angular directives.

Implementation

Create New Angular Directive

First of all, we create an Angular directive by injecting the the native element from ElementRef.

https://gist.github.com/1425076dc793360bdce20ca5e25ef377

Calculate Top Offset Of The Element

element-box-diagram

The next step is to calculate the top offset of the HTML element depending on the window. We use the .getBoundingClientRect() method that returns a DOMRect object which is the smallest rectangle which contains the entire element, including its padding and border-width.

https://gist.github.com/359132f138d71b3f7c23add0397adce0

Set Dynamic Height To Element

This method sets the calculated height to the host HTML element, using the Angular Renderer (Renderer2). If the user knows the to offset we don't need to recalculate it.

https://gist.github.com/6ca4bbc51f56fc20758bdd1ae79463a6

Observe Window Resize

We need to observe the window resize event in order to calculate the height on any change. We use the fromEvent method from rxjs to register at window's resize events and it converts them to observable. The problem here is that the events are too many when we resize the window and we have to decrease them. Thus, we use throttleTime and debounceTime from rxjs/operators to minimize the re-calculation of the dynamic height.

Tip: Unsubscribe on destroy to avoid memory leaks.

https://gist.github.com/b63bf4aa07d634b664155195af8890b6

Final Result πŸ˜‰

Great, we have done it! We have created an Angular directive that sets dynamic height to its host HTML element in a very short time.

https://gist.github.com/78da3fc24f3edc9c0054984b4f089e74

We made it to the end!πŸ‘πŸ‘πŸ‘ Hope you found this article helpful! πŸ˜‰

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment