I am using Ionic Framework and its grid system (similar to Bootstrap). However, I believe my question is more AngularJS than Ionic components.
I have the following:
 <ion-col *ngFor="let col of row.cols"></ion-col>
Note that I must set values for each col dynamically so in case col.size === 2 the above must be rendered as:
 <ion-col *ngFor="let col of row.cols" col-2></ion-col>
One way is to set all cols in advance and call *ngIfs on whichever size I want which seems like an overkill for something simpler. I have also tried to do this:
<ion-col *ngFor="let col of row.cols" [attr.col-2]="col.size === 2"></ion-col> With zero luck.
Possible values could be from 1 to 12.
Any help is much appreciated! Thanks.
You can add directive
import { Directive, ElementRef, Renderer, Input, OnInit } from '@angular/core';
@Directive({
  selector: '[dynamic-col]'
})
export class DynamicColDirective implements OnInit {
  @Input('dynamic-col') value: string;
  constructor(private el: ElementRef, private _renderer: Renderer) {}
  ngOnInit() {
    this._renderer.setElementAttribute(this.el.nativeElement, 'col-' + this.value, '');
  }
}
And then:
<ion-col *ngFor="let col of row.cols; let i = index" dynamic-col="{{i}}"></ion-col>
I hope this helps you.
Have you considered using ng-container's? They could be perfect as they don't display in the DOM.
This will still create all of your ion-col's as if they were generated using your original code but allow you to add attributes to the root element of the loop.
<ng-container *ngFor="let col of row.cols">
    <ion-col col-{{col.col-size}}></ion-col>
</ng-container>
If you have the array below:
{
  "rows": {
    "cols": {
      {
        "col-size": "2"
      },
      {
        "col-size": "4"
      },
      {
        "col-size": "6"
      }
    }
  }
}
The HTML then output is like below:
<ion-col col-2></ion-col>
<ion-col col-4></ion-col>
<ion-col col-6></ion-col>
ng-containerYou can do this in typescript and bind to the innerHtml attribute:
component.ts:
  rows = {
    cols: [
      { "size": "1" },
      { "size": "3" },
      { "size": "5" }
    ]
  }
  html: string = '';
  constructor(public navCtrl: NavController) {
    this.rows.cols.map((col) => {
      this.html += '<ion-col class="col" col-' + col.size + '></ion-col>'
    });
  }
  ...
component.html:
  <div [innerHTML]="html | safeHtml"></div>
  ...
using pipe to disable Angular’s built-in sanitization.
safeHtml.pipe.ts:
@Pipe({name: 'safeHtml'})
export class Safe {
  constructor(private sanitizer:DomSanitizer){}
  transform(value) {
    return this.sanitizer.bypassSecurityTrustHtml(value);
    // return this.sanitizer.bypassSecurityTrustStyle(value);
    // return this.sanitizer.bypassSecurityTrustXxx(style); - see DomSanitizer docs
  }
}
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With