Dynamically change margin after 5th Iteration of @for loop

49 views Asked by At

I have a practice project using Angular 17 and TailwindCSS. Currently have 35 sets of images and I want it to look like this screenshot below. This should be 140 images, 4 slides with 35 images in every slide of the carousel but as sample I only want to know how this curve thing to be done.

This is currently my html.

<div class="flex place-content-center w-full absolute top-[20%] left-auto right-auto mr-auto ml-auto">
        <div class="grid grid-flow-col grid-rows-5 gap-4">
            @for (item of carouselItems; track $index) {
                <div id="imageCard" class="w-[236px] h-[350px]">
                    <img class="w-full h-full rounded-2xl" src="{{item.imageUrl}}" alt="">
                </div>
            }            
        </div>
    </div>

If there are more efficient approach than what I currently did, please let me know.

35 image should look like

1

There are 1 answers

0
Jussi Virtanen On

I haven't worked with Angular, but here's a quick draft of the underlying methods you'll probably need. This is in React, but the principles should be framework-agnostic.

const mockArray = new Array(20).fill('')

const ImageGallery = () => {
  // How much do you want to increment the value.
  const increment = 4
  // The starting value for margin.
  let margin = 4
  return (
    <div>
      {mockArray.map((item, index) => {
        // Determine if the current index is a multiple of 5.
        const isFifth = index % 5 === 0

        // Determine if the current iteration is at or past the middle point
        const isAtHalf = mockArray.length / 2 <= index

        // If the current iteration is at the middle point or past it, decrease the margin by increment...
        if (isAtHalf && isFifth) {
          margin -= increment
        // ...or else increase it (i.e. the iteration is below the middle point)
        } else if (isFifth) {
          margin += increment
        }
        return (
          <div key={index} style={{ marginTop: `${margin}px` }}>
            {/* Your content */}
          </div>
        )
      })}
    </div>
  )
}

You might need to adjust the logic to take odd and even amounts into account.