Reputation: 1895
I have a function that gets the width of a parent div, and calculates the total width of the child elements. It will apply a css class if the parent width is bigger than the total width of all child elements. It works on page load - but now I'm trying to figure out how to do it on browser resize.
This is my function in my controller...
public setCenterClass() {
let parent = document.querySelectorAll(".container")[0];
let parentWidth = parent.clientWidth;
let children = parent.children;
let childrenWidth = 0;
for (let i = 0; i < children.length; i++) {
childrenWidth += children[i].offsetWidth;
}
if (parentWidth > childrenWidth) {
return 'center-content';
}
return;
}
and I call it from the parent div like this
<div class="container" ng-class="$ctrl.setCenterClass()" >...
It works, but if there is a better way then please let me know :)
Whats the best way to call setCenterClass() when the browser is resized? All examples I have seen seems to use directives. I'm using Angular 1.5 with components and typescript. Thanks.
Upvotes: 0
Views: 150
Reputation: 365
It isn't really what you asked for, but I'll say it anyway: I think you should use flexbox + justify-content instead. Calling a function each time the user resizes the screen isn't good, and calling the function inside ng-class is even worse performance-wise since it would get called every time the model changes.
With flexbox, you can do this:
<div id="container">
<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>
</div>
With this CSS:
#container{
height:800px;
width:1200px;
overflow-x:scroll;
display: -webkit-box;
display:flex;
justify-content:space-around;
}
.box{
height:300px;
flex:0 0 300px;
}
This way, if the children all fit inside the parent, they will be centered and spaced, but if they overflow the parent, it will become scrollable.
Here's a plunk
Upvotes: 1