Search code examples
angularangular-masonry

Angular 2 and Masonry grid third party library


I want to use Masonry Grid in Angular 2 application.

I installed this one: http://masonry.desandro.com/

with: npm install masonry-layout --save

and I include that via angular-cli.json

 "scripts": [
        "../node_modules/masonry-layout/dist/masonry.pkgd.min.js"
      ],

and that works as well.

In application if I open console in web browser and type this piece of code:

var elem = document.querySelector('#masonry-grid');
var msnry = new Masonry( elem, {
  // options
  itemSelector: '.grid-item',
  columnWidth: 200
});

Everything works as well.

Now I want to achieve that to work automatically. In component I'm using

ViewChild ( @ViewChild('masonryGrid') masonryGrid: ElementRef; )

to get the div and that replaces this line of pure JavaScript line

var elem = document.querySelector('#masonry-grid');

Now I'm struggling with creating typings.d.ts for Masonry and that part isn't yet totally clear for me.

I tried at the top of component to declare variable on this way.

declare var Masonry: any;

and then in ngAfterViewInit() to do this

new Masonry(this.masonryGrid.nativeElement, {
  // options
  itemSelector: '.grid-item',
  columnWidth: 200
});

Everything was compiled as well and I don't see any errors in console, but Masonry is not instantiated and it doesn't work.

Edit

It started to work. It seems how there was problem with angular-cli webpack. Sometimes it doesn't recognize changes automatically. It said "Nothing changed" in console. I restarted server and it started to work.


Solution

  • There is a ported Masonry module for Angular 2.

    It can be found here.

    You need to import it into your main module, or a shared module.

    import { MasonryModule } from 'angular2-masonry';
    
    @NgModule({
      imports: [
        MasonryModule
      ]
    })
    

    A sample component looks like this:

     @Component({
       selector: 'my-component',
       template: `
         <masonry>
            <masonry-brick class="brick" *ngFor="let brick of bricks">
            {{brick.title}}</masonry-brick>
         </masonry> `
     })
     class MyComponent {
       bricks = [
         {title: 'Brick 1'},
         {title: 'Brick 2'},
         {title: 'Brick 3'},
         {title: 'Brick 4'},
         {title: 'Brick 5'},
         {title: 'Brick 6'}
      ]
     }