When using a ngFor loop, the @Input('index') parameter will remain set to zero throughout the iterations

component-setup.html

<app-module 
  *ngFor="let module of (modules | async); let m = iteration"  
  [iteration]="m" 
  [module]="module">
</app-module>

module-rendering.ts

export class ModuleRenderingComponent implements OnInit, OnChanges {
  @Input('iteration') iteration: number;
  constructor(private apiService: ApiService) {
    this.iteration = 0;
    console.log(this.index)
  }
}

Why is the iteration not updating when passed to the input field? When I display "iteration" in component-setup.html, ngFor correctly assigns the value of 1 to the input field.

Answer №1

Make sure to always initialize the index variable to zero in the constructor, and then use console.log to display its value after assignment. This will show that it consistently remains as zero on your console.

this.index = 0;
console.log(this.index)

Additionally, remember that the input is not set in the constructor by Angular. It's best to utilize Angular lifecycle methods like OnInit (ngOnInit) for this purpose.

Here are some helpful tips:

  • Avoid using the same name for your input as the property.
  • Assign a default value directly to your property declaration.
  • Prefer using Angular lifecycle events over the constructor whenever possible.

For a tested solution, try this:

<app-product
  *ngFor="let product of products | async; let i = index"
  [index]="i"
  [product]="product"
></app-product>
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-product',
  template: '<div>{{index}} - {{ product | json }}</div>',
})
export class ProductComponent {
  @Input() index = 0;
  @Input() product: unknown;

  constructor(private store: Store) {
    // The value will be zero because the input is not yet set by Angular.
    console.log(this.index);
  }

  ngOnInit() {
    // Once initialized, expect the value to be greater than or equal to zero.
    console.log(this.index);
    // You can also perform additional operations with this.store here.
  }
}

Hint: Consider utilizing OnChanges to handle input changes more effectively.

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

The Angular Pipe is designed to extract values from Enum types in a generic way that can be applied

I am having an issue with enums in my code. The enum contains strings, but it does not work properly with integers as indexes. For example, RoleTypesEnum[0] returns undefined. To solve this problem, I created a custom Pipe. export enum RoleTypesEnum { ...

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Retrieve the predetermined value from the dropdown menu option

I currently have two classes with a mapping structure as follows: User *--------------------1 Sexe Users are listed in the file list-users.component.html. When selecting a user for modification, I am redirected to the modify-user.component.html B ...

What is the process for adding an item to the dictionary state?

I'm currently working on a function to push an object to the state in my code. The goal of this function is to duplicate the first state object and append it to the end of the state array. addField() { const index = (this.state?.fields.length) -1 ...

Spread operator in TypeScript does not interact properly with a specific type

Currently, I am working with a redux-style reducer in ngrx that returns a specific type. However, I have encountered an issue where the TypeScript linter fails to catch invalid properties when using the spread operator in my return object. Below is the in ...

Tips for resolving Circular dependency issue in node.js?

While working on a post request, I encountered an issue with the code below: try{ const _id = await db.collection('UserInformation').insertOne(userObj); await db.collection('LoggedInUser').updateOne({ userId: _id }, { '$set&ap ...

How can I handle returning different types of Observables in my Angular application?

I can't seem to get an observable to return properly. The mergeMap function inside my code doesn't appear to be executing at all. Here are the relevant snippets of code: book.service.ts import {HttpClient, HttpHeaders} from '@angular/comm ...

Troubleshooting Issue: Ionic 3 and Angular ngForm not transmitting data

Attempting to create a basic crud app with ionic 3, I am encountering an issue where new data cannot be inserted into the database. The problem seems to lie in the PHP server receiving an empty post array. Below is my Ionic/Angular code: Insert.html < ...

What is the method for converting textarea input into an array in Angular?

I am experiencing an issue with my Angular form that has a textarea. I am using a string array for the formControl, and upon checking the email addresses entered upon ngModelChange, I am assigning them to the array. However, when I submit the form, the arr ...

Please input the number backwards into the designated text field

In my react-native application, I have a TextInput where I need to enter numbers in a specific order such as 0.00 => 0.01 => 0.12 => 1.23 => 12.34 => 123.45 and so on with each text change. I tried using CSS Direction "rtl" but it didn' ...

I encountered TS2345 error: The argument type X cannot be assigned to the parameter type Y

Currently, I am delving into the world of Angular 8 as a beginner with this framework. In my attempt to design a new user interface with additional elements, I encountered an unexpected linting error after smoothly adding the first two fields. The error m ...

Incorporating Bootstrap Extensions into Angular 8

Recently delving into Angular, I've been attempting to incorporate a Bootstrap Plugin called Bootstrap Toggle into Angular 8. Below are the steps I've taken: First, I installed bootstrap, jquery, popper.js, and bootstrap-toggle. In the angular. ...

Import a Component Dynamically Using a Variable in AngularJS

I am attempting to dynamically load a component using a variable, but I keep running into an "Uncaught Error: Template parse errors". How can I achieve this successfully? <app-{{ this.plugin.component }}></app-{{ this.plugin.component }}> ...

Troubleshooting Problem with Kendo UI Integration in Angular 2

Attempting to follow the steps outlined in http://www.telerik.com/kendo-angular-ui/getting-started/ Encountered this error message in the browser console. No errors found on the server side. <button kendoButton (click)="onButtonClick()" [ERROR ->][ ...

Using props in React can be declared either as a `type` or an `interface`

I am working with React code export default class MyComponent extends Component<Props,State> I'm trying to figure out whether I should define my props using a type or an interface. type Props = { isActive: Boolean, onClick: Function } ...

What sets apart npm correlation-id from uuid?

Can you please explain the distinction between the uuid and correlation-id npm packages? It seems that correlation-id actually utilizes the uuid package internally.. When would you recommend using correlation-id over uuid? Important: I am not utilizing ...

Updating the hostbinding to dynamically add a class

Consider the given component below: @Component({ selector: 'my-component', templateUrl: './my-component.html', style: [` :host.isSticky { position: sticky; top: 0; } `], changeDetection: ChangeDetectionStra ...

Having trouble retrieving the SSM Parameter during deployment using CDK

Currently, I am facing a strange issue as I attempt to retrieve a parameter for my pipeline using the CDK SSM Parameter library: CfnParameter at 'nonProdAccountId.Parameter' should be created in the scope of a Stack, but no Stack found Despite t ...

Applying a Typescript Generic to enhance the functionality of the API fetcher

I've written a simple function to enhance fetch functionality. I am currently exploring how TypeScript Generics can be utilized to define the Type for 'data' in the return. const apiFetchData = async ( url: string, options = {}, ): P ...

Identify the specific directive selector utilized within the template by examining multiple directive selectors

My directive has two selectors, dirA and dirNotA, and I need to determine which one was used within the directive itself. I want to avoid creating multiple directives or using parameters in order to achieve this. Ideally, I would like to have a single dire ...