我想实现 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/