从对象值动态设置col-*值

use*_*620 6 html javascript ionic-framework ionic2 angular

我正在使用Ionic Framework及其网格系统(类似于Bootstrap).但是,我相信我的问题是AngularJS比Ionic组件更多.

我有以下内容:

 <ion-col *ngFor="let col of row.cols"></ion-col>
Run Code Online (Sandbox Code Playgroud)

请注意,我必须动态设置每个col的值,以防col.size === 2上述内容必须呈现为:

 <ion-col *ngFor="let col of row.cols" col-2></ion-col>
Run Code Online (Sandbox Code Playgroud)

一种方法是提前设置所有cols并在我想要的任何尺寸上调用*ngIfs,这对于更简单的事情来说似乎有些过分.我也试过这样做: <ion-col *ngFor="let col of row.cols" [attr.col-2]="col.size === 2"></ion-col>运气不好.

可能的值可能来自1 to 12.任何帮助深表感谢!谢谢.

Ole*_*sar 7

你可以添加指令

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, '');
  }
}
Run Code Online (Sandbox Code Playgroud)

然后:

<ion-col *ngFor="let col of row.cols; let i = index" dynamic-col="{{i}}"></ion-col>
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助你.