让Packery / Masonry使用angular2
发布时间:2020-12-17 10:23:40 所属栏目:安全 来源:网络整理
导读:我正在尝试让Packery / Masonry在一个组件上工作. Packery正在检测容器,但是它的高度为零表示内容未加载,即使我正在使用imagesLoaded.我已经尝试过使用各种生命周期钩子,但它们都有相同的结果,所以有点丢失我错的地方. import {BlogService} from './blog.se
我正在尝试让Packery / Masonry在一个组件上工作. Packery正在检测容器,但是它的高度为零表示内容未加载,即使我正在使用imagesLoaded.我已经尝试过使用各种生命周期钩子,但它们都有相同的结果,所以有点丢失我错的地方.
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,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',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 }); }); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |