Sharing Top Content from the Angular-sphere.

Responsive Equal Heights with an Angular 2+ Directive

  • Another problem you’ll see is that when you scale down your browser, the height will be updated (grow taller).
  • It should always match the height of the tallest object, and resize when screen size changed, like this:-
  • We loop the list with *ngFor in our template and display each item .
  • Let’s create our match height directive.
  • Always Reset all child elements’ height first

Let’s look at a very common use case. You has a list of items, you need to display all nicely on screen in card…

@JavaScriptKicks: Responsive Equal Height with Angular Directive by @jecelynyeen #javascript #angularjs via @JavaScriptKicks

Let’s look at a very common use case. You has a list of items, you need to display all nicely on screen in card form.

It looks okay but you want all cards to always maintain same height. It should always match the height of the tallest object, and resize accordingly when screen size changed, like this:-

We can achieve this with by using creating a custom directive.

Interesting? Let’s code.

Let’s look at our main component.

in our template and display each item accordingly.

Please note that in this example, I am using Boostrap 4 to style the CSS, but it’s not neccesary.

There are a few ways to match height. In this tutorial, we will match height by using CSS class name.

are the children.

as the attribute value.

coming from? That is the custom directive that we are going to build next!

Let’s create our match height directive.

Let’s breakdown what should we do step by step:-

Let’s code it.

I guess the code is very expressive itself.

Now that we have completed our match height logic, let’s use it.

Refresh your browser and you should see all the card are with same height!

Now, let’s resize your browser. The card height is not adjusted automatically until you refresh the broswer again. Let’s update our code.

We need to listen to the window resize event and update the elements’ height.

Another problem you’ll see is that when you scale down your browser, the height will be updated accordingly (grow taller). However, when you scale up your browser, the height is not updated (not shrink down).

Why is this happening? It is because once the card size grow taller, all content can fit in and no height adjustment needed.

of all elements before we recalculate the tallest height. We do this after step 1.

That’s it. Remember that whenever we need to manipulate DOM element, it’s recommend that we do it in directive. Creating a custom directive and listening to custom event is easy with Angular Directive.

Our directive work well with any elements including nested component too. Check out the source code for another 2 more examples.

Happy coding!

Responsive Equal Heights with an Angular 2+ Directive

Comments are closed, but trackbacks and pingbacks are open.