Querying For The Closest Parent Element in Angular

Netanel Basal
Netanel Basal
Published in
2 min readNov 22, 2017

--

Imagine that you have a component with a nested structure. You’ve found a case where one of the children needs to run some functionality on one of its closest parents.

To demonstrate this, let’s assume we have the following structure:

Let’s say the widget-item element needs to add a specific class to the closest parent, which matches the widget-content class selector when a specific condition is true.

Your initial instinct will probably be to use the method we all know from JQuery — the closest() method.

For example:

The above code will work, but as professional Angular developers, we need to use the tools Angular provides us with to achieve the same result. Let’s see how we can do this.

First, we need to create a directive whose selector will match the required parent element. I like to call these ‘Query Directives’.

The next thing we need to do is to expose an API to add our custom class to the element.

Here, we are using the HostBinding decorator to add the overflow class to our host component.

Now, we can obtain a reference to our directive inside the widgetItem component, using the Host decorator.

Specifies that an injector should retrieve a dependency from any injector until reaching the host element of the current component.

and call the addOverflow() method when necessary.

Live demo from StackBlitz. Try editing the code yourself.

👂🏻 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment for over seven months, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.

Follow me on Medium or Twitter to read more about Angular, Vue and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.