Reputation: 667
I have a ng for loop with a component inside them. I am running a resizing function that sets the size of the component for each component. This all works great on load but on window resize the resizing function only fires for the last component in the list and not every component. Below is my parent for loop.
<masonry [options]="myOptions">
<div masonry-brick class="masonry-item" *ngFor="let item of (feedsList$ | async);let i = index">
<grid-item [item]="item" [index]="i" [listLength]="(feedsList$ | async).length"></grid-item>
</div>
</masonry>
Below is the component resize function and the call.
constructor() {
window.onresize = (e) => {
this.calculateItemSize()
}
}
calculateItemSize() {
const item = Math.ceil(this.index / 11);
const groupIndex = 11 * item;
let itemIndex = null
if (groupIndex == 11) {
itemIndex = this.index + 1
} else {
itemIndex = (this.index + 1) - (groupIndex - 11)
}
let dividedWidth = this.elemRef.nativeElement.parentElement.parentElement.clientWidth / 3
let width, height
switch (itemIndex) {
case 2: {
width = dividedWidth * 2 + 'px'
height = dividedWidth * 2 + 'px'
break;
}
case 4: {
width = dividedWidth * 2 + 'px'
height = dividedWidth + 'px'
break;
}
case 7: {
width = dividedWidth * 2 + 'px'
height = dividedWidth * 2 + 'px'
break;
}
default: {
width = dividedWidth + 'px'
height = dividedWidth + 'px'
break;
}
}
this.renderer.setStyle(this.elemRef.nativeElement.parentElement, 'width', width)
this.renderer.setStyle(this.elemRef.nativeElement.parentElement, 'height', height)
}
Upvotes: 0
Views: 208
Reputation:
Your code isn't working because you're redefining the listener of your window everytime you run this
window.onresize = (e) => {
this.calculateItemSize()
}
This literally means
bind this function to the variable
window.onresize
So yeah, your last item is using it, and the others aren't.
The solution would be to move this code in the parent component, and use a @ViewChildren
decorator to get all of your grid items, then run the function inside all of your children.
Upvotes: 2