Looping and passing arguments to a method
I have the following code
@inherits MyCompBase
@for(var i=0; i< Counter;i++)
{
<div onclick=@( x=>ItemClicked(i))>this is item @i</div>
}
using Microsoft.AspNetCore.Blazor.Components;
using System;
namespace WebApplication2.Shared
{
public class MyCompBase : BlazorComponent
{
public int Counter { get; set; } = 4;
public void ItemClicked(int value)
{
Console.WriteLine(value);
}
}
}
I expected it to write value "i" to be written to console when the div is clicked. it is always writing "4". what am I missing?
That's because i=4 at the end of the loop. i isn't 'rendered' like @i, it's just variable, and that the moment you click it's 4
Thanks for answering, @floreseken !
I think to work around this issue you could use a new component instead of the div that capture the value of i as part of its state and then uses that state to write to the console.
Change your for loop to something like this:
@for(var i=0; i< Counter;i++)
{
var local_i = i;
<div onclick=@( x=>ItemClicked(local_i))>this is item @i</div>
}
Thanks!. Much better solution