How to display an nth-column layout using ionic 2 GridLayout

n

n
n
nIonic’s grid system is based on flexbox, a CSS feature supported by all devices that Ionic supports. The grid is composed of three units — grid, rows and columns. nnnnnColumns will expand to fill their row, and will resize to fit additional columns.
nTo have a two rows and three equal columns grid, the structure will look like this:
n

n  n    width-33n    width-33n    width-33n  nn  n    width-33n    width-33n    width-33n  nn

nAs you can see we have two rows and three columns in the above layout which is pretty easy. This is very easy to layout when you have static data you want to display.nnnnn
n
nJust recently I was building an app that requires using ionic 2 grid layout, but it was so challenging laying out the structure because my data was coming from call to external API. As you might have know I was also using ngFor.
n
nI tried something like this:
n
n

n n  n    n     n      n        n          {{item.title}}n        n        n      n    n   n  nn

n
nThis did not work for me.nn
n

nThe Solution

nAfter a lot trials, I finally solve the issue by doing these:
n
n
n

 ionViewDidLoad() {n    this.catSerivce.getCategories()n      .subscribe(categories => {n        this.categories = categoriesn        this.rows = Array.from(Array(Math.ceil(categories.length / 3)).keys());n      },n      error => console.log(error));n  }nn

nTake a look at line 5 of the code above, I have a variable call rows where I stored the number of rows that the returned data will have. I user Array.from and also divide the length of my categories by three (number of columns).nn
n
nI then have this as my html markup:
n
n

 n    n      n        n          n          n            n              {{category.name}}n                        n          n        n      n    n  n

n
nI found this approach very flexible because if I want a four columns grid I can just replace 3 with 4 in both my markup and in my typescript code.nnnnnn
n
nThe complete code can be found here.
n
nDo you know a better approach of doing this? If so please share.
n
nHappy coding.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top