Unending Angular 4 Array Iteration

Looking to utilize *ngFor to iterate over my array elements multiple times. Here's what I have:

Within the component:

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

In the template:

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

Desired output in the render:

a, b, c, d, e

After clicking on 'a':

d, e, a, b, c

After clicking on 'e':

c, d, e, a, b

Any suggestions or tips would be greatly appreciated! Thanks in advance!

Answer №1

Give this solution a try to solve your issue

 <div *ngFor="let character of characters" (click)="customFunction(character)">{{character}}
</div>

customFunction(selectedCharacter){
    let maxLength = 4; // tweakable
    let index = 0, length = str2.length;
    let isFound = false;
    let array1 = [], array2 = [], array3 = [];
    for(;index<length;index++){
         if(str2[index] == selectedCharacter){
             for(j=0;j<maxLength && (index+j)< length ; j++){
                array1.push(str2[index+j]);
                index++;
             }
             isFound = true;
         }else if(!isFound){
                array2.push(str2[index]);
         }else{
                array3.push(str2[index]);
         }

    }

    this.characters = array3.concat(array2);
    this.characters = this.characters.concat(array1);   

}

Answer №2

To achieve this, simply utilize two lists with ngIf: the first list will display the letters before or including the currentLetter, while the second list will show the letters after the 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>

https://i.sstatic.net/oRN8f.png https://i.sstatic.net/JxUXq.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reactive form enabled for Angular control

In order to meet the required format for a social security number input field using reactive forms, it must adhere to the following conditions: The format should be ###-##-####. Limited to 9 digits without including the dashes (11 characters with dashes) ...

Changes are reflected in the service variable, but they are not updating in the component

I am facing an issue with a variable that is supposed to track the progress of image uploads. The variable seems to be working fine, but it remains undefined in my component. Upload Service method uploadProfilePic(url:string, user_id:string, image:any) { ...

Unit testing in Angular 2: Triggering hover events

In my setup, I have a template for a specific component (MyCmp) that looks like this <template ngFor let-r [ngForOf]="range" let-index="index"> <span>{{ index < 5 ? 'Y' : 'N' }}, {{r.data}}</span> <i (mousee ...

Dealing with a series of challenging npm problems consecutively

npm WARNING: Deprecated Usage Please note that global '--global' and '--local' configurations are now deprecated. Please use '--location=global' instead. Error Code: ERESOLVE Unable to resolve dependency tree. While reso ...

The source 'http://localhost:4200' is being denied access by the CORS policy when using SignalR with .NET Core and Angular

In my Angular application, I am using SignalR to fetch real-time data and a .NET Core 2.2 API for the back-end. However, upon running the project, I encounter CORS errors in the browser console. VehicleHub.cs using Microsoft.AspNetCore.SignalR; using Sys ...

Discovering the Angular HostBinding feature with parameter capabilities

Within my component, there is a numeric input that determines the width of the component. I need to dynamically set the width based on this input value using classes, as the width calculation relies on Sass variables that may change over time. I have thre ...

Dropdown within Datatable does not automatically select the bound option [PrimeNG]

Hey there! I'm a trainee just entering the world of frontend development, so apologies in advance if my question seems silly or if my code looks messy (any corrections are greatly appreciated). In my project, I have a Dropdown element inside a Datata ...

Switch up the default font in your Nuxt 3 and Vuetify 3 project

I've been doing a lot of searching on Google, but I can't seem to find the solution. It seems like the challenge might be that the Nuxt 3 + Vuetify 3 combination isn't widely used yet? My current task is to implement a custom default font. ...

Error message encountered in Typescript eslint: File extension "ts" is missing in import statement for the specified file

I am encountering an issue with my Node/Express application created using Typescript. The problem lies in eslint throwing an error that says: Missing file extension "ts" for "./lib/env" import/extensions Below is the content of my .eslintrc file: { ...

Using a Type Guard in Typescript to check if an environment variable matches a key in a JSON object

I am currently working on creating a Type Guard to prevent TypeScript from throwing an error on the final line, where I attempt to retrieve data based on a specific key. TypeScript is still identifying the environment variable as a string rather than a rec ...

Having Trouble with Angular Form Reset and Receiving the Error Message "Trying to Reference a Destroyed View: detectChanges"

Upon successfully saving a value, I trigger a form reset. This involves calling a service method to send data to an API. this.customerService.saveSupplier({ customerId: Context.customerId, supplier: supplier }).subscribe(res => { this.pageReset(); ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here&apo ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

Angular 8 HTTP Interceptor causing issues with subscriptions

I'm currently in the process of setting up an Angular 8 project that will allow me to mock API calls using HTTP INTERCEPTORS. My approach involves adding a --configuration=mock flag to my ng serve script so that the interceptor is injected into my app ...

Error: nativeElement.getBoundingClientRect method is undefined

While working on my application test, I encountered a challenge when trying to validate the returns of two getBoundingClientRect functions. The first one, which is in an HTMLElement located by ID, gave me no trouble as I was able to mock its return success ...

The ng-content directive fails to display the component containing the host attribute

I can't figure out why ng-content isn't displaying the component with a host attribute. When inspecting the generated HTML DOM, the attribute is present in the host tag but ng-content doesn't have any children. @UPDATE: Following @Naren M ...

Is it possible for an object to be undefined in NextJS Typescript even after using a guard

Hey there, I could really use some help with a React component I'm working on. This is one of my initial projects and I've encountered an issue involving fetching async data. Below is the current state of my solution: import { Component } from &q ...

Encountering difficulties in setting up ng zorro using Angular CLI for installation

I'm facing an issue with installing ng-zorro. Every time I try to run the command ng add ng-zorro-antd, I encounter an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/c ...

Utilizing process.env in TypeScript can be a bit tricky as dot notation is not effective for accessing its properties

When I set my scripts to: "start": "NODE_ENV=development nodemon dist/Server.js", I am encountering an issue when trying to access NODE_ENV in my code. Both dot and bracket notation return undefined: The dependencies in my project are: "@types/node": "^8. ...