javascript - 如何在不创建数组的情况下使用 NgFor 来生成矩阵 UI 模式

标签 javascript html angular typescript angular2-template

我想实现 UI 矩阵模式,它应该动态生成。 通过接收输入参数,它应该决定什么是 UI 矩阵模式尺寸: 例如 9X3 元素: pattern 9x3 elements

我使用 Angular2.js、typescript、SCSS。

html 模板和 .ts 外观:

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>

** 此代码无法在此环境中运行:)*

问题: 如何在不创建数组的情况下使用 NgFor 来生成 UI。 我的意思是,如果我将接收输入 x=9 和 y=3,它应该构建 9X3 的 UI 矩阵模式。 请指教:)

谢谢。

最佳答案

创建自定义 STRUCTURAL DIRECTIVE重复模板 N 次。

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);
   }
}

使用方法如下

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

关于javascript - 如何在不创建数组的情况下使用 NgFor 来生成矩阵 UI 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36621771/

相关文章:

angular - 语法错误: Cannot use import statement outside a module using @ionic-native/health in Angular/Nx/jest app

javascript - 需要帮助在日语中格式化 MomentJS 中的日期

javascript - 尝试使用 html 和 javascript 显示模态,但单击后没有任何显示

html - 向右浮动 2 个 Div,一个在另一个之上

javascript - 阻止在移动设备上查看我的网站

javascript - 从可观察同步获取数据。 Angular

javascript - 如何用数组中的值替换字符串中的字符?

javascript - 将jquery中的逗号分隔列表转换为无序列表

javascript - 当创建一个只运行一次的函数时,重新定义应该在该函数之前还是之后进行?

Angular4如何使用flatMap链接forkJoin