Search code examples
angularngfor

Equivalent of simple "for" (iterating with index) of C# in Angular


In a razor page I can write:

 @for (int i = 1; i <= Model.TotPages; i++)
    {
        <div class="pagmenu">
            @if (i == Model.CurPage)
            {
                @Html.ActionLink(i.ToString(), "Index", "Home", new { curPage = i, catId = Model.CatId, discounted = Model.Discounted, search= Model.Search }, new { @class = "btn btn-primary" })
            }
            else
            {
                @Html.ActionLink(i.ToString(), "Index", "Home", new { curPage = i, catId = Model.CatId, discounted = Model.Discounted, search = Model.Search }, new { @class = "btn btn-default" })
            }
        </div>
    }

What is the equivalent in angular? *ngFor is the equivalent of foreach not of for, as I understand it.


Solution

  • if Angular you only can iterating over arrays, well you can create an array "on fly" using "repeat", see this SO

    //in ts
    n=10;
    
    <div *ngFor="let a of ' '.repeat(n).split('');let i=index">
      {{i}}
    </div>
    

    or using a function to return an array

    //in .ts
    n=10;
    getFoolArray(n)
    {
        return new Array(n)
    }
    
    <div *ngFor="let a of getFoolArray(n);let i=index">
      {{i}}
    </div>
    

    Another option is create a directive repeat, see this SO answer