Angular 2-ngFor uso de números en lugar de colecciones


...por ejemplo...

<div class="month" *ngFor="#item of myCollection; #i = index">
...
</div>

Es posible hacer algo así...

<div class="month" *ngFor="#item of 10; #i = index">
...
</div>

...sin apelar a una solución no elegante como:

<div class="month" *ngFor="#item of ['dummy','dummy','dummy','dummy','dummy',
'dummy','dummy','dummy']; #i = index">
...
</div>

?

 100
Author: Marco Jr, 2016-04-01

7 answers

Dentro de su componente, puede definir una matriz de números (ES6) como se describe a continuación:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
    this.numbers = Array(5).fill(4); // [4,4,4,4,4]
  }
}

Vea este enlace para la creación del array: La mejor manera de crear un array de enteros a partir de 1..20 en JavaScript .

Luego puede iterar sobre esta matriz con ngFor:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

O en breve:

@Component({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}
 110
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-11 08:04:43

No todavía no hay un método para ngFor usando números en lugar de colecciones, Por el momento, *ngFor solo acepta una colección como parámetro, pero puede hacer esto mediante los siguientes métodos:

Usando tubería

Pipe.ts

import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
  transform(value, args:string[]) : any {
    let res = [];
    for (let i = 0; i < value; i++) {
        res.push(i);
      }
      return res;
  }
}


<ul>
  <li>Method First Using PIPE</li>
  <li *ngFor='#key of 5 | demoNumber'>
    {{key}}
  </li>
</ul>

Usando matriz numérica directamente en HTML (View)

<ul>
  <li>Method Second</li>
  <li *ngFor='#key of  [1,2]'>
    {{key}}
  </li>
</ul>

Usando el método de división

<ul>
  <li>Method Third</li>
  <li *ngFor='#loop2 of "0123".split("")'>{{loop2}}</li>
</ul>

Usando la creación de una nueva matriz en el componente

<ul>
  <li>Method Fourth</li>
  <li *ngFor='#loop3 of counter(5) ;#i= index'>{{i}}</li>
</ul>

export class AppComponent {
  demoNumber = 5 ;

  counter = Array;

  numberReturn(length){
    return new Array(length);
  }
}

Demo de trabajo

 54
Author: Pardeep Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-29 07:13:45

No podía soportar la idea de asignar una matriz para la repetición simple de componentes, así que he escrito una directiva estructural. En la forma más simple, eso no hace que el índice esté disponible para la plantilla, se ve así:

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

@Directive({ selector: '[biRepeat]' })
export class RepeatDirective {

  constructor( private templateRef: TemplateRef<any>,
             private viewContainer: ViewContainerRef) { }

  @Input('biRepeat') set count(c:number) {
    this.viewContainer.clear();
    for(var i=0;i<c;i++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}

Http://plnkr.co/edit/bzoNuL7w5Ub0H5MdYyFR?p=preview

 8
Author: pdudits,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-26 20:45:46

Puedes usar lodash:

@Component({
  selector: 'board',
  template: `
<div *ngFor="let i of range">
{{i}}
</div>
`,
  styleUrls: ['./board.component.css']
})
export class AppComponent implements OnInit {
  range = _.range(8);
}

No probé el código, pero debería funcionar.

 3
Author: Alex Po,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-08 20:53:51

Lo resolví así usando Angular 5.2.6 y TypeScript 2.6.2:

class Range implements Iterable<number> {
    constructor(
        public readonly low: number,
        public readonly high: number,
        public readonly step: number = 1
    ) {
    }

    *[Symbol.iterator]() {
        for (let x = this.low; x <= this.high; x += this.step) {
            yield x;
        }
    }
}

function range(low: number, high: number) {
    return new Range(low, high);
}

Se puede usar en un componente como este:

@Component({
    template: `<div *ngFor="let i of r">{{ i }}</div>`
})
class RangeTestComponent {
    public r = range(10, 20);
}

Comprobación de errores y aserciones omitidas a propósito de brevedad (por ejemplo, lo que sucede si el paso es negativo).

 3
Author: Per Edin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-24 11:09:21

Por favor, encuentre adjunta mi solución dinámica si desea aumentar el tamaño de una matriz dinámicamente después de hacer clic en un botón (Así es como llegué a esta pregunta).

Asignación de las variables necesarias:

  array = [1];
  arraySize: number;

Declare la función que añade un elemento al array:

increaseArrayElement() {
   this.arraySize = this.array[this.array.length - 1 ];
   this.arraySize += 1;
   this.array.push(this.arraySize);
   console.log(this.arraySize);
}

Invoca la función en html

  <button md-button (click)="increaseArrayElement()" >
      Add element to array
  </button>

Iterar a través de matriz con ngFor:

<div *ngFor="let i of array" >
  iterateThroughArray: {{ i }}
</div>
 0
Author: Jan Clemens Stoffregen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-26 13:23:34

Una manera más simple que he probado

También puede crear una matriz en su archivo de componentes y puede llamarla con la directiva *ngFor regresando como una matriz .

Algo como esto ....

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-morning',
  templateUrl: './morning.component.html',
  styleUrls: ['./morning.component.css']
})
export class MorningComponent implements OnInit {

  arr = [];
  i: number = 0;
  arra() {
    for (this.i = 0; this.i < 20; this.i++) {
      this.arr[this.i]=this.i;
    }
    return this.arr;
  }

  constructor() { }

  ngOnInit() {
  }

}

Y esta función se puede utilizar en su archivo de plantilla html

<p *ngFor="let a of arra(); let i= index">
value:{{a}} position:{{i}}
</p>
 0
Author: Alok Panday,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 04:48:05