2016-05-11 38 views
5

我正試圖讓包裝/砌體在組件上工作。 Packery正在檢測容器,但給它一個零高度,暗示即使我正在使用imagesLoaded,內容尚未加載。我已經嘗試過使用各種生命週期鉤子,但它們都有相同的結果,所以丟失的位置與我出錯的地方相同。讓包裝/砌體與angular2一起工作

import {BlogService} from './blog.service'; 
import {Blog} from './blog.model'; 
import {Component, ElementRef, OnInit, AfterViewInit} from '@angular/core'; 
import {LinkyPipe} from '../pipes/linky.pipe'; 

declare var Packery: any; 
declare var imagesLoaded: any; 

@Component({ 
    moduleId: module.id, 
    selector: 'blog', 
    templateUrl: 'blog.component.html', 
    providers: [BlogService], 
    pipes: [LinkyPipe] 
}) 

export class BlogComponent implements OnInit, AfterViewInit { 
    blogs: Blog[]; 
    errorMessage: string; 
    constructor(private _blogService: BlogService, public element: ElementRef) { } 
    ngOnInit() { 
    this.getBlogs(); 
    } 

    ngAfterViewInit() { 
    let elem = this.element.nativeElement.querySelector('.social-grid'); 
    let pckry; 
    imagesLoaded(elem, function(instance) { 
     console.log('loaded'); 
     pckry = new Packery(elem, { 
     columnWidth: '.grid-sizer', 
     gutter: '.gutter-sizer', 
     percentPosition: true, 
     itemSelector: '.social-card' 
     }); 
    }); 
    } 

    getBlogs() { 
    this._blogService.getPosts() 
     .subscribe(
     blogs => this.blogs = blogs, 
     error => this.errorMessage = <any>error); 
    } 
} 

回答

3

好,我的工作了,我需要使用AfterViewChecked代替然而,當我第一次嘗試它結束了它永無止境的循環,因爲這是發射每次DOM的變化,從而你會看到有一個幾乎沒有額外的檢查,所以它只發射一次。仍然不確定這是否是正確的方法,但現在可行。

import {BlogService} from './blog.service'; 
import {Blog} from './blog.model'; 
import {Component, ElementRef, OnInit, AfterViewChecked} from '@angular/core'; 
import {LinkyPipe} from '../pipes/linky.pipe'; 
declare var Packery: any; 
declare var imagesLoaded: any; 
@Component({ 
    moduleId: module.id, 
    selector: 'coco-blog', 
    templateUrl: 'blog.component.html', 
    providers: [BlogService], 
    pipes: [LinkyPipe] 
}) 
export class BlogComponent implements OnInit, AfterViewChecked { 
    blogs: Blog[]; 
    errorMessage: string; 
    isGridInitialized: boolean; 
    constructor(private _blogService: BlogService, public element: ElementRef) { } 
    ngOnInit() { 
    this.getBlogs(); 
    } 
    ngAfterViewChecked() { 
    if (this.blogs && this.blogs.length > 0 && !this.isGridInitialized) this.initGrid(); 
    } 
    getBlogs() { 
    this._blogService.getPosts() 
     .subscribe(
     blogs => this.blogs = blogs, 
     error => this.errorMessage = <any>error); 
    } 
    initGrid() { 
    this.isGridInitialized = true; 
    let elem = document.querySelector('.social-grid'); 
    let pckry; 
    imagesLoaded(elem, function(instance) { 
     console.log('all images are loaded'); 
     pckry = new Packery(elem, { 
     percentPosition: true, 
     itemSelector: '.social-card', 
     gutter: 20 
     }); 
    }); 
    } 
}