Is it possible to implement a different termination condition when using *ngFor in Angular 2?

After countless hours of searching on Google, I have yet to discover a method for implementing an alternative stop condition for loops created with the *ngFor directive.

By default, *ngFor loops end with this condition: index < array.length. Is there a way to conclude a loop with a different condition, such as i < myVariable?

I am currently developing a picture gallery that operates in the following manner:

<div *ngFor="let pic of pics; let i = index">
    <div *ngIf="whichRowType(i) == 3">
        <small>pic[whichIndex(i)].id</small>
        <small>pic[currentIndex + 1].id</small>
        <small>pic[currentIndex + 2].id</small>
    </div>

    <div *ngIf="whichRowType(i) == 2">
        <small>pic[whichIndex(i)].id</small>
        <small>pic[currentIndex + 1].id</small>
    </div>

    <div *ngIf="whichRowType(i) == 1">
        <small>pic[whichIndex(i)].id</small>
    </div>
</div>

In this specific case, I create a new row every three pictures where each row can display one, two, or three images respectively.

The issue arises from the fact that the index of the first picture in each row is always less than the index used to display the row. To ensure all pictures are displayed correctly, I need the flexibility to modify the ending condition of my *ngFor loop.

Your assistance in this matter would be greatly appreciated. Thank you!

Answer №1

*ngFor has a feature that allows access to the last item:

  <div *ngFor="let pic of pics; let i = index; let last=last">
    <div *ngIf="last">
      ...
    </div>
  </div>

For more information, check out Implementing ngClassEven ngClassOdd for angular 2

Answer №2

After much trial and error, I finally found a solution to my problem in a rather unconventional way... Instead of adding another end condition, I decided to create a loop using an array length determined by a function. Within this loop, I iterated through another array containing my images.

It would be great if Angular had a built-in feature for this! I appreciate all the help from everyone!

Here is an example of how I resolved it :

<div *ngFor="let galleryIndex of galleryIndexes; let i = index">
    <div *ngIf="whichRowType(galleryIndex) == 3">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
        <small>pics[currentIndex + 1].id</small>
        <small>pics[currentIndex + 2].id</small>
    </div>

    <div *ngIf="whichRowType(galleryIndex) == 2">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
        <small>pics[currentIndex + 1].id</small>
    </div>

    <div *ngIf="whichRowType(galleryIndex) == 1">
        <small>pics[setCurrentIndex(galleryIndex)].id</small>
    </div>
</div>

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

Is the statement true in JavaScript if either true or true or false?

I have implemented this code snippet to prevent my page from being iframed: window.onload = function(){ try { if (window.parent && window.parent.location.hostname !== "app.herokuapp.com"){ throw new Error(); } catch (e){ //do something ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

Can you choose to declare a type in TypeScript, or is it required for every variable

Has anyone encountered a problem similar to this? type B = a ? 'apple' | 'grape' | 'orange' : 'apple' | 'grape'; // This code results in an ERROR! const x = (a: boolean, b: B) => console.log('foo&a ...

Issue with tooltip not displaying attribute data-bs-title in Angular 17 with Bootstrap version 5.3

I am currently developing an Angular version 17 application and implementing a dynamic tooltip feature. The tooltip content will be supplied through a @Input() into the component. While a static tooltip works fine, I am facing an issue when trying to make ...

What is the best way to maintain the order of variadic types for conditionally inferred conditional types?

Here is the type definition that I am working with: type Inner<Type> = Type extends Wrapper<infer U>[] ? U[] : never; Additionally, I have a function with the following signature: function myFunc<From extends Wrapper[], To>( values: ...

What is the purpose of RouterLink and RouterOutlet in Angular?

RouterLink and RouterOutlet are both angular attribute directives that assist in navigating to a specific route from the collection of routes. Once a matching route is found, the corresponding component is loaded, and its template is rendered on the browse ...

Angular Universal does not fully render on the server side

Currently, my project involves integrating Angular 4 with Angular Universal and Knockout. The main objective is to have the Angular application generate HTML on the server side for SEO purposes. As part of this process, I need to utilize KnockoutJs to bin ...

Minimize unnecessary re-renders when working with dynamically nested components in React

My project state includes a nested list of animals, like this: {"europe":{"air":{name:"warbler", points:0}}} Each component is dynamically generated based on this data, with a button at the animal level triggering callbac ...

What could be causing the Angular 5 error: "Cannot find exported module 'OpaqueToken'."?

I am currently in the process of upgrading my Angular 4 application to Angular 5. During this upgrade, I encountered the following error message: ERROR in src/app/application/services/generated/variables.ts(1,10): error TS2305: Module '"..../no ...

Angular - choose an input field and then tap on a different button to increase the value

Currently, I am working on adding a functionality to my material table that consists of several input fields. My goal is to create a function where selecting an input field will allow me to increment its value using a separate '+' button. The is ...

Issue with dependencies: Incorrect value passed to `ts.resolveTypeReferenceDirective` causing a problem

This issue is really frustrating me. I'm currently working on this repository. Everything seems to be fine on the client side, but when it comes to the server side, I encountered the following problem: MacBook-Pro$ yarn dev yarn run v1.22.19 warning . ...

The loop termination condition is malfunctioning - C

I'm currently working on a homework assignment that involves dynamic arrays, so I decided to experiment with some basic programs to help me understand how they work. #include <stdio.h> #include <string.h> #include <stdlib.h> int m ...

Encountering an issue with the form onSubmit function in React TypeScript due to an incorrect type declaration

I have a function below that needs to be passed into another component with the correct type definition for updateChannelInfo, but I am encountering an issue with the type showing incorrectly: const updateChannelInfo = (event: React.FormEvent<HTMLFormEl ...

Is the regex returning the correct result?

I need to discuss the date field with a format of YYYYMMDD, as shown below: zod.string().max(8).regex(new RegExp('^(19[0-9][0-9]|20[0-9][0-9]|[0-1][0-9]{3})(1[0-2]|0[1-9])(3[01]|[0-2][1-9]|[12]0)$')); The value provided is 20001915. The definit ...

Using React along with TypeScript to specify the type of useState as an object containing key/value pairs of strings

I'm currently working in React with typescript and attempting to set the type of useState as an object containing string key/value pairs. Despite searching on SO, I haven't found a solution yet. I've experimented with <{ [key: string]: s ...

Waiting for an async method in an Angular test: Tips and tricks

When working on an Angular application, I utilize various tools libraries and some of my code that involve: Declarations with asynchronous behavior The use of setInterval within which I do not want to wait. While attempting to implement solutions like fa ...

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

Implementing a Toggle Feature in React Components for Looping Elements

Hey everyone, I'm encountering a problem on my development site and could use some assistance. The issue I'm facing involves looping through a data file to create project cards with show more/show less functionality for displaying/hiding descript ...

Checking for coverage in unit testing of the RxJS Observable catch block

I need to increase unit test coverage on a code block that includes a catch block calling a method to handle errors. Here's the code snippet in question: return this._http.get(/someurl) .map((response: Response) => { le ...

Utilizing React TypeScript within Visual Studio

Utilizing the most recent editions of Visual Studio and Visual Studio Code, I have initiated a project using create-react-app with TypeScript react scripts version. My objective is to host my project within a .NET Core web application that I've estab ...