katoid / angular-grid-layout

Responsive grid with draggable and resizable items for Angular applications.
https://katoid.github.io/angular-grid-layout
MIT License
436 stars 60 forks source link

Emit layoutUpdated event when adding or removing items from grid #115

Open vlaca99 opened 4 months ago

vlaca99 commented 4 months ago

When implementing adding or removing items in grid, layoutUpdated event is not emitted and x and y values are not updated accordingly. Is there a way to trigger layoutUpdated event on add/remove?

kova98 commented 2 months ago

I had the same issue, see removeItem and addItemToLayout in the playground example.

Just recalculate the y afterwards if you're going to use the value anywhere else.

removeItem(item: KtdGridLayoutItem & { id: string }) {
  this.layout = this.layout.filter(
    (layoutItem) => layoutItem.id !== item.id,
  );

  // recalculate y position of all items
  this.layout.forEach((layoutItem, index) => {
    const previousItem = this.layout[index - 1];
    if (previousItem && layoutItem.y - previousItem.y > 1) {
      layoutItem.y = previousItem.y + 1;
    }
  });
}

On add, make sure to create a new variable rather than changing the existing one

  addItem(x: number, y: number, width: number, height: number, id: string) {
    const item: KtdGridLayoutItem = {
      x: x,
      y: y,
      w: width,
      h: height,
      id: id,
    };

    this.layout = [...this.layout, item];
  }
golnush-shams commented 1 month ago

i had the same issue , but i handled it by using ktdGridCompact. you can reCompact your layouts and get new positions programmatically. but consider if you want to use ktdGridCompact you need to set compactOnPropsChange peoperty to false to avoid duplicate compacting. i hope this is usefull.

const compactLayout = ktdGridCompact(this.layout, this.compactType, this.cols);
this.layout = compactLayout;