0

I want to use *ngFor and repeat my array elements myltiple times. Like this:

In component:

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

In template:

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

And I wanna to see something like this in render:

a, b, c, d, e

And after click on 'a':

d, e, a, b, c

And after click on 'e':

c, d, e, a, b

Any ideas? :) Thanks for help!

2 Answers 2

1

Try this it will resolve your problem

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

}
Sign up to request clarification or add additional context in comments.

Comments

0

Just use two lists with ngIf: the first list renders the letters before currentLetter or currentLetter itself, while the second list renders the letters after 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.