How can I use NgFor without creating arrays to generate matrix UI pattern

此生再无相见时 提交于 2019-12-05 11:22:23

Create custom STRUCTURAL DIRECTIVE which repeats template N times.

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

Use as follows

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

Building arrays just to iterate over them seems lavish. Creating a Directive to replace ngFor is sort of redundant.

Instead you could use a Pipe returning an Iterable and use it like this:

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

For an implementation of such a Pipe have a look at my other answer on Repeat HTML element multiple times using ngFor based on a number.

Günter Zöchbauer

You can either create an helper array like shown in Repeat HTML element multiple times using ngFor based on a number using new Array(count).fill(1) and use ngFor to iterate over this array or you can implement your own structural directive like NgFor that doesn't iterate over an array but instead uses a count as input.

After reading all answers I managed to solve it:

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

It works for me. Thank You all!!!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!