gpt4 book ai didi

angular - 让 Packery/Masonry 与 angular2 一起工作

转载 作者:太空狗 更新时间:2023-10-29 17:27:51 25 4
gpt4 key购买 nike

我正在尝试让 Packery/Masonry 在组件上工作。 Packery 正在检测容器,但将其高度设置为零,这表明即使我使用的是 imagesLoaded,内容仍未加载。我尝试过使用各种生命周期 Hook ,但它们都有相同的结果,所以我不知道哪里出错了。

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);
}
}

最佳答案

好的,我发现我需要使用 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
});
});
}
}

关于angular - 让 Packery/Masonry 与 angular2 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37159337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com