Angular Gridster2: How do I trigger a function in item after resize?

1.3k Views Asked by At

I would like to trigger a function in my widget component after the GridsterItem is resized. How do I do that? I know that Gridster2 has event callback after resized is finished, but how do I use that to trigger something on my widget component?

In my LayoutComponent:

export class LayoutComponent implements AfterViewInit {
    options: GridsterConfig = {
      // yada yada
      itemResizeCallback: (x, y) => this.itemResized(x, y)
    };

    layout: GridsterItem[] = [];

    constructor() { }

    ngAfterViewInit(): void {
    }

    itemResized(x: any, y: any) {
      // How do I call the function doSomething() in PieWidgetComponent here?
    }

    async addItem() {
        this.layout.push({ x: 0, y: 0, cols: 1, rows: 1, widgetComponent: PieWidgetComponent });
    }
}

<gridster [options]="options" #myGrid>
    <gridster-item *ngFor="let item of layout" [item]="item">
        <ng-container *ngComponentOutlet="item.widgetComponent"></ng-container>
    </gridster-item>
</gridster>

In my WidgetComponent:

export class PieWidgetComponent implements OnInit {
    constructor() {
    }

    ngOnInit(): void {
    }

    public doSomething(): void {
      // How do I trigger this from LayoutComponent's after item has been resized?
      console.log("ALOHA");
    }
}

<div style="text-align:center; background-color: aquamarine;">
    My widget
</div>
1

There are 1 best solutions below

0
On

Using https://www.npmjs.com/package/ng-dynamic-component library (to pass input to dynamic component) and an event service, it can be achieved as follows:

event.service.ts to broadcast the resize event to widget components:

@Injectable()
export class EventService {

  public eventEmitter: EventEmitter<Event>;

  constructor() {
    this.eventEmitter = new EventEmitter();
  }

  public onItemResized(id){
    this.eventEmitter.emit(id);
  }
}

home.component.ts

constructor(public eventService:EventService) {
}

itemResized(x: any, y: any) {
    this.eventService.onItemResized(x.inputs.id);
}

async addItem(id) {
  this.layout.push({ x: 0, y: 0, cols: 1, rows: 1, widgetComponent: PieWidgetComponent, inputs: {id: id} });
}

home.component.html

<gridster [options]="options" #myGrid>
  <gridster-item *ngFor="let item of layout" [item]="item">
     <ng-container *ngComponentOutlet="item.widgetComponent;
                            ndcDynamicInputs: item.inputs"
                            ></ng-container>
  </gridster-item>
</gridster>

pie-widget.component.ts

@Input() id;
  
constructor(public eventService:EventService) {
}

ngOnInit(): void {
   this.eventService.eventEmitter.subscribe((id) => {
    if(this.id === id){
      this.doSomething()
    }
   })
}

public doSomething(): void {
  // How do I trigger this from LayoutComponent's after item has been resized?
  console.log("ALOHA");
}