どんだけIonicでMasonryレイアウトやりたいんだお前って感じですが、前回のJSプラグイン版に続き、今度はAngularプラグインを使ってみた記録です。
ngx-masonryモジュールのリポジトリはこちらです。
GitHub – gethinoakes / ngx-masonry
もともとMasonryのAngularモジュールとして公開されていたangular2-masonryが古くなったため、フォークして新しいバージョンに対応したものらしいです。
If I have the time I will look into further improvements, but please do not expect support as I don’t have the time for that.
Google翻訳<時間があれば、さらなる改善を検討しますが、時間がないのでサポートを期待しないでください
……とのことなので、この先動かなくなっても仕方ないなあという気持ちでありがたく使わせていただきます。
プロジェクトのフォルダにインストールします。
$ npm install ngx-masonry –save
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular'; ・・・ import { NgxMasonryModule } from 'ngx-masonry' // ←追加 @NgModule({ declarations: [ ・・・ ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), NgxMasonryModule, // ←追加 ], ・・・ }) export class AppModule {}
import { Component } from '@angular/core'; import { IonicPage, NavController } from 'ionic-angular'; import { NgxMasonryOptions } from 'ngx-masonry'; // ←MasonryOptions使うとき必要 @IonicPage() @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { public masonryOptions: NgxMasonryOptions = { transitionDuration: '0.2s', gutter: 10, resize: true, percentPosition: true, }; masonryItems = [ { picture: './assets/images/image01.jpg' }, { picture: './assets/images/image02.jpg' }, { picture: './assets/images/image03.jpg' }, { picture: './assets/images/image04.jpg' }, { picture: './assets/images/image05.jpg' }, { picture: './assets/images/image06.jpg' }, { picture: './assets/images/image07.jpg' }, { picture: './assets/images/image08.jpg' }, { picture: './assets/images/image09.jpg' }, { picture: './assets/images/image10.jpg' } ]; constructor(public navCtrl: NavController) { } } <ion-content padding> <ngx-masonry [options]="masonryOptions" [updateLayout]="updateMasonryLayout"> <ngxMasonryItem class="grid-item" *ngFor="let item of masonryItems"> <img src="{{item.picture}}"> </ngxMasonryItem> </ngx-masonry> </ion-content> page-home { ngx-masonry { width: 100%; } .grid-item { width: calc(25% - 10px); margin-bottom: 10px; @media screen and (max-width:768px){ width: calc(50% - 10px); } } }
オプションでfitWidth:true
にするとpercentPosition
がうまく動きません。
gutter
で指定した分の横幅が余分になってカラム落ちしてしまうので、cssで指定する横幅はgutter分だけマイナスすると良いっぽい。
社内で「IonicでjQuery使いたくないのよね」とやっぱり言われたので、使うとしたらこれかなー。
仕上がりはこんな感じ。
あと、Masonryの意味はこういうのです。