Search code examples
angularngfor

In my angular project, why is the index variable of my iterated(ngFor) components becoming a string instead of a number


I created an iteration of all the data in the component so each element becomes a card using *ngFor.

<ng-container *ngFor="let card of cardsInfo; index as i">
  <app-card
    id="{{ card.id }}"
    index="{{ i }}"
    [url]="url"
    [cardLocation]="isDisplayed(card.id)"
  >

As you can see the index is an input for the CardComponent.

Originally, I had @Input() index: number; in the CardComponent but when I tried to access that number and use it with another number(For example: card.index === this.displayedCardIndex - 1, the app would not work. I logged card.index === 0 in the console and got false even though the element with an index of 0 should have been true but it was false. I logged card.index, this.displayedCardIndex to the console and got 0 0 but the second 0 was purple telling me it was a different type, a number type and the first was white, of the type string. To confirm this I console logged typeof card.index and it confirmed to me that it was a string.

Why is it making it a string? I assume it is because it is coming from the HTML template. Is there a way to make angular pass it as of type number when that is what it is so I don't have to parseInt it every time I use it or do something like that in the CardComponent? To me that just feels like a hack and would prefer to not do that.


Solution

  • When you use handlebars, the value is taken as something to be displayed. To bind the actual value, try

    [index]="i"