[Fixed] Implementing Gridstack 3 in Angular

Issue

I’m following this example, trying to implement it in Angular.

I import as follows (no jQuery dependencies):

import * as GridStack from 'gridstack/dist/gridstack-h5';

And the code

ngAfterViewInit() {
    
  var items = [
      {content: 'my first widget'}, // will default to location (0,0) and 1x1
      {w: 2, content: 'another longer widget!'} // will be placed next at (1,0) and 2x1
   ];

    var grid = GridStack.init();
    grid.load(items);
}

But all I see is static divs instead of a grid, and there are no errors. What’s missing?

Solution

Please post your HTML template.

Double check your config from GridStack Read Me, if you are using an ngfor then you need to see step 3 and invoke this on your main div $('.grid-stack').gridstack();

  1. You must install:

yarn add gridstack
// or
npm install --save gridstack
  1. You must import it into angular component 2A or 2B for HTML:

  • 2A For your answer Typescript like so:
import 'gridstack/dist/gridstack.min.css';
import GridStack from 'gridstack';

You should now have gridstack-h5.js gridstack native js version like here

  • 2B For others lookging to do it in HTML optional, like so:

    <script src="node_modules/gridstack/dist/gridstack-h5.js"></script>

    <link href="node_modules/gridstack/dist/gridstack.min.css" rel="stylesheet"/>

  1. What is your HTML template, like here

  ngAfterViewInit() {
        setTimeout(() => {
            $('.grid-stack').gridstack();
            this.gridStack = $('.grid-stack').data('gridstack');
        }, 300); //This MUST finish after dynamic data is retrieved for ngfor, and calling these statements in another area just doesn't work
    }

Leave a Reply

(*) Required, Your email will not be published