Búsqueda de sitios web

javascript - ¿Cómo puedo usar NgFor sin crear matrices para generar un patrón de interfaz de usuario en forma de matriz?


Me gustaría implementar un patrón de matriz de interfaz de usuario, que debería generarse de forma dinámica. Al recibir un parámetro de entrada, debería decidir cuáles serían las dimensiones del patrón de matriz de interfaz de usuario: por ejemplo, 9X3 elementos: patrón 9x3 elementos

Uso Angular2.js, TypeScript, SCSS.

La plantilla HTML y el .ts se ven así:

import {Component, Input, OnInit} from 'angular2/core';
import {NgFor} from 'angular2/common';

@Component({
  selector   : 'game-pattern',
  moduleId   : module.id,
  templateUrl: 'game-pattern.component.html',
  styleUrls  : ['game-pattern.component.css'],
  directives : [NgFor],
})
export class GamePatternComponent implements OnInit {
  @Input('CardType') public cardType: number;

  public horizontalElementLocation: number;
  public verticalElementLocation: number;
  public rows: number[]     = [];
  public elements: number[] = [];
  public y: number;
  public x: number;

 // public cardType = 3;
 constructor() {
    this.cardType = 3;
  }

  public ngOnInit() {
    console.log('cardType ' + this.cardType);
    this.chooseGamePattern();
  }

  public chooseGamePattern() {
    if (this.cardType === 3) {
      this.horizontalElementLocation = 9;
      this.verticalElementLocation   = 3;
    }

    for (this.y = 0; this.y < this.verticalElementLocation; this.y++) {
      this.rows[this.y] = 0;
      for (this.x = 0; this.x < this.horizontalElementLocation; this.x++) {
        this.elements[this.x] = 0;
      }
    }
  }
}
<div id="game-pattern" >
  <div class="pattern-row" *ngFor="#row of rows">
    <div class="big-circle" *ngFor="#elemnt of elements"> 
      <div class="small-circle"></div>
    </div>
  </div>
</div>

** este código no pudo ejecutarse en este entorno :)

Pregunta: ¿Cómo puedo usar NgFor sin crear arrays para generar la interfaz de usuario? Quiero decir, si recibo la entrada x=9 y y=3, debería construir un patrón de matriz de interfaz de usuario de 9X3. Por favor, aconseje :)

Gracias.

Respuesta #1

Crea una DIRECTIVA ESTRUCTURAL personalizada que repita la plantilla N veces.

import {TemplateRef, ViewContainerRef, Directive, Input} from 'angular2/core';

@Directive({
   selector: '[mgRepeat]'
})
export class mgRepeatDirective {
   constructor(
       private _template: TemplateRef,
       private _viewContainer: ViewContainerRef
   ) { }

   @Input('mgRepeat')
   set times(times: number) {
       for (let i = 0; i < times; ++i)
           this._viewContainer.createEmbeddedView(this._template);
   }
}

Usar como sigue

<div id="game-pattern" >
  <div class="pattern-row" *mgRepeat="verticalElementLocation">
     <div class="big-circle" *mgRepeat="horizontalElementLocation"> 
        <div class="small-circle"></div>
     </div>
 </div>
</div>

Respuesta #2

Construir arrays solo para iterar sobre ellos parece extravagante. Crear un Directive para reemplazar ngFor es algo redundante.

En su lugar, podrías usar un Pipe que devuelva un Iterable y usarlo así:

<div *ngFor="let i of 30|times">{{ i }}</div>

Para una implementación de tal Pipe, eche un vistazo a mi otra respuesta sobre cómo repetir un elemento HTML varias veces usando ngFor basado en un número.

Artículos relacionados