Angular2和砌体网格第三方库

Angular 2 and masonry grid third party library

我想在 Angular 2 应用程序中使用 Masonry Grid。

我安装了这个:http://masonry.desandro.com/

与:npm install masonry-layout --save

我通过 angular-cli.json

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

这也行得通。

在应用程序中,如果我在 Web 浏览器中打开控制台并键入这段代码:

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

一切正常。

现在我想实现自动工作。那我做了什么?

在我使用的组件中

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

得到 div 并替换这行纯 javascript 行

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

现在我正在努力为 Masonry 创建 typings.d.ts,这部分对我来说还不是很清楚。

我试过在组件顶部用这种方式声明变量

declare var Masonry: any;

然后在 ngAfterViewInit() 中执行此操作

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

一切都已编译,我在控制台中没有看到任何错误,但 Masonry 未实例化且无法运行。

我们将不胜感激。

编辑:

它开始起作用了。 angular-cli webpack 似乎有问题。有时它不会自动识别更改。它在控制台中说 "Nothing changed" 。我重新启动服务器,它开始工作。

Angular 2.

有一个移植的 Masonry 模块

可以找到here.

您需要将其导入主模块或共享模块。

import { MasonryModule } from 'angular2-masonry';

@NgModule({
  imports: [
    MasonryModule
  ]
})

示例组件如下所示:

 @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'}
  ]
 }