2017-09-27 70 views
0

我想使用* ngFor並重復我的數組元素多次。就像這樣:Angular 4無限數組循環

在組件:

letters: Array<string> = [a, b, c, d, e]; 
currentLetter: string= c; 

模板:

<div *ngFor="let letter of letters" (click)="currentLetter = letter">{{letter}}</div> 

而且我想看到的東西像這樣渲染:

A,B,C,d, e

並點擊'a'後:

d,E,A,B,C

,並點擊 'E' 之後:

C,d,E,A,B

任何想法? :) 感謝您的幫助!

回答

1

試試這個它能夠解決您的問題

<div *ngFor="let letter of letters" (click)="myMethod(letter)">{{letter}} 
</div> 


myMethod(selectedLetter){ 
    let postLen = 3; // configurable 
    let i=0, len =str1.length; 
    let foundFlag = false; 
    let arr1 = [], arr2 = [], arr3 = []; 
    for(;i<len;i++){ 
     if(str1[i] == selectedLetter){ 
      for(k=0;k<postLen && (i+k)< len ; k++){ 
       arr1.push(str1[i+k]); 
       i++; 
      } 
      foundFlag = true; 
     }else if(!foundFlag){ 
       arr2.push(str1[i]); 
     }else{ 
       arr3.push(str1[i]); 
     } 

    } 

    this.letters = arr3.concat(arr2); 
    this.letters = this.letters.concat(arr1); 

} 
0

只需使用兩個與ngIf的列表:第一個列表呈現currentLettercurrentLetter之前的字母本身,而第二個列表呈現currentLetter之後的字母。

<ng-container *ngFor="let letter of letters; index as i"> 
    <button *ngIf="i>=letters.indexOf(currentLetter)" (click)="currentLetter = letter">{{letter}}</button> 
</ng-container> 
<ng-container *ngFor="let letter of letters; index as i"> 
    <button *ngIf="i<letters.indexOf(currentLetter)" (click)="currentLetter = letter">{{letter}}</button> 
</ng-container> 

result1 result2