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.