Using dual index variables in Angular 4's ngFor loop for iterating through arrays

Is there a way to generate unique index numbers for items printed only on Saturdays? Specifically, I want the index to start from 0 once Saturday begins and continue incrementing. The rest of the options should have the same index numbers. Any suggestions on how to achieve this?

Check out my code on StackBlitz

Answer №1

This is the exact purpose for which the modulo operation was designed...

It's important to note that you cannot have two different indexes in your array. It wouldn't make sense, as they would have the same value anyway.

Instead, utilize the modulo operator (known as such in French, not sure about the translation):

<div *ngFor="let item of items; let i = index">
  <span *ngIf="i % 7 === 5">It's Saturday!</span>
</div>

Snippet:

const days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
const month = [...days, ...days, ...days, ...days];

month.forEach((day, i) => {
  if (i % 7 !== 5) { return; }
  console.log(day);
});

EDIT ONE When dealing with an unordered array of days, the best approach to "reset an index" is to split your array into multiple ones.

If you want to reset on Saturdays, consider something like this:

array=["monday","monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "saturday", "sunday"];
splitted = this.array.reduce((p, n) => {
  if (n === 'saturday') { p.push([n]); return p; }
  p[p.length - 1].push(n);
  return p;
}, [[]]);

<p *ngIf="options != 'saturday' ">
  {{i}}. First category: Value{{i}}
  <p>
    <p *ngIf="options == 'saturday'" style="color:red">
      {{i}}. Saturday: Value{{i}}
    </p>
</div>

Check out the updated stackblitz.

EDIT TWO Hopefully, this is the correct solution now! Simply create a counter with a getter method and reset the counter to zero once the lifecycle is completed.

private counter;

get saturdayCounter() {
  return this.counter++;
}

ngAfterContentChecked() {
  this.counter = 0;
}
<p *ngIf="options == 'saturday'" style="color:red">
  {{i}}. Saturday: Value{{saturdayCounter}}
</p>

View the working stackblitz here.

Answer №2

Create a fresh array using the elements from your existing "array"

let freshArray:any[]=[];
let counter:number=0;

this.array.forEach((element, index)=>{
   if (element=="saturday")
   {
     freshArray.push({type:1, index:counter});
     counter++;
   }
   else
     freshArray.push({type:0, index:index});
}) 

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

Tips for sending a form using Angular 1.5.8 and Java Servlet via POST method

After reading various tutorials and online documentation, I'm still struggling to figure out how to pass parameters from a JSP form. Below is the JavaScript script I am using: var app = angular.module('myApp', []); app.controller('Form ...

Create a personalized attribute for division automation

Is it possible to automatically divide a dynamically populated ListView in jQuery-mobile into two groups based on the attribute values (Downloaded/Not downloaded)? Some listitems have the attribute status="true" while others have status="false". Here is t ...

A 'select all' checkbox in a PHP 'foreach loop' with JavaScript

I am in search of a solution to implement JavaScript in the given code block. My goal is to have the checkbox with id = alles automatically check all the checkboxes that are generated within the while loop. <form id="andere" name="andere" action="<? ...

Troubleshooting: Bootstrap 5 Alert not Displaying on Website

I'm experiencing an issue trying to display a bootstrap alert in my HTML code. Here is the code I'm using: <div class="alert alert-success alert-dismissible fade show" role="alert"> text & ...

Angular Universal: Execution of ngAfterViewInit occurring on the server side rather than the client side

While working on my server-rendered Angular application with Angular 17, I ran into a curious issue revolving around the ngAfterViewInit lifecycle hook. The situation arises when I call an init function within ngAfterViewInit, which relies on an API reques ...

Encountering a permission issue while trying to execute npm install -g @angular/cli command

I recently started using Angular and am working on a new project. However, when I try to execute the following command: npm install -g @angular/cli I encounter the error message below: npm WARN checkPermissions Missing write access to /usr/local/lib/no ...

Exploring data segments in Knockoutjs using various models

I'm trying to figure out why Knockout.js won't allow me to access specific parts of the model data. Could it be because I am binding the model to the div that contains all the submodels (such as the Form in this example), or am I approaching this ...

Tips for adjusting the width of the box on a BoxPlot chart in Apex charts

Currently, I am utilizing apexcharts(version 3.35.3) within an Angular project and I am looking to adjust the width of the box. After reviewing the documentation for apexcharts, I have not been able to find any specific option that allows me to modify the ...

The CSS selector functions as expected when used in a web browser, however, it

While conducting test automation using Selenium, I typically rely on css selectors to find elements. However, I recently came across a peculiar issue. I observed that in certain cases, the css selector works perfectly when tested in the browser console. Fo ...

Stop YouTube Video in SlickJS Carousel, Remove Placeholder Image Forever

Feel free to check out the CodePen example: http://codepen.io/frankDraws/pen/RWgBBw Overview: This CodePen features an ad with a video carousel that utilizes SlickJS. There are a total of 3 YouTube videos included in the carousel, with the SlickJS ' ...

generating a dynamic string array containing particular elements

Given a string "hello @steph the email you requested is [email protected] for user @test" The goal is to transform it into: ['hello ', <a href="">@steph</a>, 'the email you requested is <a href="/cdn-cgi/l/email-protect ...

CSS - starting fresh with animations

I am facing an issue with a CSS animation that I created. Everything seems to be working correctly, but I need to complete it by setting the input type to reset the animation. Below is the CSS code snippet that should reset the animation: $('button& ...

I found myself puzzled by the error message "Module protobufjs not found."

I am currently utilizing the node library known as node-dota2. I have completed all the necessary steps required by node-dota2, as outlined on this site: https://github.com/Arcana/node-dota2#installation-and-setup 1. Installed it using npm 2. Created a fil ...

The declared type 'never[]' cannot be assigned to type 'never'. This issue is identified as TS2322 when attempting to pass the value of ContextProvider using the createContext Hook

I'm encountering an issue trying to assign the state and setState to the value parameter of ContextProvider Here's the code snippet:- import React, { useState, createContext } from 'react'; import { makeStyles } from '@material-ui ...

Guidance on transferring information from a parent component to an Angular Material table child component

Currently, I am implementing an angular material table with sorting functionality. You can view the example here: Table Sorting Example I intend to transform this into a reusable component so that in the parent component, all I have to do is pass the colu ...

Create a separate server session specifically for handling an ajax request?

Currently, I am working with a collection of PHP server-side scripts that manage user session state by utilizing PHP sessions extensively for authenticated users. For the client side within a mobile application and using Jquery ajax, I am striving to esta ...

How to prevent links from being affected by the Gooey effect in D3

Issue: When applying the Gooey effect, the links are also affected, resulting in a teardrop shape instead of a circle. The code snippet includes a dragged() function that allows users to detach node 1 from node 0 and reconnect them by dragging. The code s ...

Unexpected issue encountered during the Angular 9 compilation process

Since migrating to Angular 9, I've encountered an issue with my feature branch after a rebase. Trying to switch to develop and update it using pull origin develop, everything seemed fine until I came across this error that's leaving me puzzled: h ...

Sort through the files for translation by utilizing a feature within Typewriter

I am looking to implement Typewriter in a project that involves translating many C# files into TypeScript using WebEssentials. Is there a way to configure the template so that only class files containing a specific attribute are translated in this mann ...

Arranging information extracted from an XML document following an ajax request

Here is a snippet of XML data sample to work with: <?xml version="1.0" encoding="ISO-8859-1"?> <CATALOG> <CD> <TITLE>Empire Burlesque</TITLE> <ARTIST>Bob Dylan</ARTIST> <COUNTRY>U ...