使用带有Angular 2的Packery

时间:2017-02-09 15:23:08

标签: angular webpack angular-cli packery

我无法使用angular-cli和typescript 2.0让Packery使用Angular 2。 我使用的是Packery 1.4.1以及DefinitelyTyped中该版本的打字稿定义。

问题是在使用ng serve运行项目时无法找到对Outlayer的Packery引用。

具体而言,引发以下异常:

  

TypeError:无法设置属性' position'未定义的       at Object.utils.extend(eval at webpackJsonp.82.module.exports

以下是我的项目代码。

来自angular-cli.json的

脚本部分:

"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js"],

我也尝试添加依赖的js文件,但抛出的异常是相同的:

"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js",
        "../node_modules/get-size/get-size.js",
        "../node_modules/outlayer/outlayer.js",
        "../node_modules/ev-emitter/ev-emitter.js",
        "../node_modules/fizzy-ui-utils/utils.js",
        "../node_modules/desandro-matches-selector/matches-selector.js"
        ],

app.component.ts:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
declare var Packery: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit
{
  @ViewChild('grid') grid;

  private pckry: any;
  constructor() {}

  ngAfterViewInit(){
    this.pckry = new Packery(this.grid, {
      itemSelector: '.grid-item'});
  }
}

app.component.html

<div #grid class="grid">
  <div class="grid-item"></div>
  <div class="grid-item"></div>
</div>

我想帮助解决如何使用或不使用打字器在Angular 2中运行Packery(vanilla js对我来说没问题)。

1 个答案:

答案 0 :(得分:1)

以上问题是我没有使用&#34; nativeElement&#34;网格的属性。这将有效:

var packery = new Packery(this.grid.nativeElement, {
itemSelector: '.grid-item', columnWidth: 100 });

angular-cli脚本部分中唯一需要的脚本如下:

"scripts": [
        "../node_modules/packery/dist/packery.pkgd.js"        
        ]

添加可拖动性使用&#34; npm install draggability --save&#34;并将另一个脚本添加到angular-cli的脚本部分:

"scripts": [
        "../node_modules/packery/dist/packery.pkgd.min.js",
        "../node_modules/draggabilly/dist/draggabilly.pkgd.min.js"        
        ]

然后也更新组件类:

import { Component, ViewChild, AfterViewInit } from '@angular/core';
declare var Packery: any;
declare var Draggabilly: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit
{      
  @ViewChild('grid') grid;   

  constructor() {}

  ngAfterViewInit(){
      var packery = new Packery(this.grid.nativeElement, {
        itemSelector: '.grid-item', columnWidth: 100 });

      packery.getItemElements().forEach( function( itemElem ) {
        var draggie = new Draggabilly( itemElem );
        packery.bindDraggabillyEvents( draggie );
      });         
  }
}
相关问题