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



Ionic’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. Columns will expand to fill their row, and will resize to fit additional columns.
To have a two rows and three equal columns grid, the structure will look like this:

  
    width-33
    width-33
    width-33
  

  
    width-33
    width-33
    width-33
  

As 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.

Just 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.

I tried something like this:


 
  
    
     
      
        
          {{item.title}}
        
        
      
    
   
  


This did not work for me.

The Solution

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


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

Take 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).

I then have this as my html markup:

 
    
      
        
          
          
            
              {{category.name}}
                        
          
        
      
    
  

I 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.

The complete code can be found here.

Do you know a better approach of doing this? If so please share.

Happy coding.

No comments

Powered by Blogger.