How to set ion-grid col width dynamically

 <ion-grid>
   <ion-row>
     <ion-col [width]="theColWidth">This column will take of space dynamically</ion-col>
   </ion-row>
</ion-grid>

How can I set the col width dynamically like this?

this.theColWidth = ‘width-10’

What I do in this case is not give it any width, and put an ngIf on the second ion-col.

Example:

<ion-row>
  <ion-col>This always shows up and takes whatever space left</ion-col>
  <ion-col *ngIf="hasData" width-80>This only shows up if we have data, and takes 80% of width.</ion-col>
</ion-row>

In some cases I have tried with ngIf like your way, but in other cases, I need set col width dynamically.

Just looked at the source code, looks like the grid is 100% SASS and it uses attributes (not classes). That means you can’t change it programmatically (AFAIK).

:sweat_smile:
Wish Ionic team make it programmatically.:yum:

I just did some quick search. Turns out you can set attributes dynamically with Angular 2.

So in your case it would look something like this:

<ion-grid>
  <ion-row>
    <ion-col [attr.width-20]="someBooleanValue"></ion-col>
    <ion-col *ngIf="someBooleanValue">Some other stuff</ion-col>
  </ion-row>
</ion-grid>

Also I think you can add multiple [attr.], just like how you can add multiple [class.<class name>] and [style.<property name>]

Reference: http://stackoverflow.com/a/37498398

4 Likes

I got it to work, but it only works with CSS attributes, doesn’t work with Angular 2 component attributes (example: button colors or styles).

<ion-grid>
  <ion-row>
    <ion-col [attr.width-20]="someBooleanValue? true : null"></ion-col>
    <ion-col *ngIf="someBooleanValue">Some other stuff</ion-col>
  </ion-row>
</ion-grid>

When the value is null, Angular will remove the attribute completely. And when the value is true it will add width-20="true" which still works fine.


Update: it works with <button> too. But it only works with the defined inputs/attributes ( such as outline, solid, clear … etc see here for more ).

The colors aren’t defined as attributes so you can add your custom colors (defined in app.variables.sass) to the button.

Update #2 Nevermind :grin: … It works with the colors too. Just gotta use the [color] attribute on the color. I just saw this

5 Likes

:+1::v::vulcan::ok_hand:

@ihadeed, thank you so much for perfect workaround. What do you think this is bug or feature? Should it fixed?

I don’t think this is a bug. It’s just the way Angular 2 works.

This is fantastic! I was able to use the<ion-col [attr.size-lg]="some value === true ? 12 ? 6"> to dynamically change the column widths based on content and it’s AMAZING!!!

2 Likes