diff --git a/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor b/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor new file mode 100644 index 0000000..c517f41 --- /dev/null +++ b/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor @@ -0,0 +1,9 @@ +@typeparam TItem +@{ + int i = 0; + foreach (TItem value in In ?? Enumerable.Empty()) + { + var item = new ValueWithIndex(value!, i++); + @ChildContent!(item); + } +} \ No newline at end of file diff --git a/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor.cs b/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor.cs new file mode 100644 index 0000000..cb85dd3 --- /dev/null +++ b/Source/Lib/Morris.Blazor.ControlFlow/ForEachWithIndex.razor.cs @@ -0,0 +1,16 @@ +using Microsoft.AspNetCore.Components; +using System.Collections.Generic; + +namespace Morris.Blazor.ControlFlow; + +public partial class ForEachWithIndex +{ +#if NET6_0_OR_GREATER + [EditorRequired] +#endif + [Parameter] public IEnumerable? In { get; set; } +#if NET6_0_OR_GREATER + [EditorRequired] +#endif + [Parameter] public RenderFragment>? ChildContent { get; set; } +} diff --git a/Source/Lib/Morris.Blazor.ControlFlow/ValueWithIndex.cs b/Source/Lib/Morris.Blazor.ControlFlow/ValueWithIndex.cs new file mode 100644 index 0000000..cbcb2b2 --- /dev/null +++ b/Source/Lib/Morris.Blazor.ControlFlow/ValueWithIndex.cs @@ -0,0 +1,13 @@ +namespace Morris.Blazor.ControlFlow; + +public readonly struct ValueWithIndex +{ + public T Value { get; } = default!; + public int Index { get; } = 0; + + public ValueWithIndex(T value, int index) + { + Index = index; + Value = value; + } +} diff --git a/Source/Tutorials/ForEachExample/Pages/FetchData.razor b/Source/Tutorials/ForEachExample/Pages/FetchData.razor index 9d60730..6bd7adb 100644 --- a/Source/Tutorials/ForEachExample/Pages/FetchData.razor +++ b/Source/Tutorials/ForEachExample/Pages/FetchData.razor @@ -7,39 +7,62 @@

This component demonstrates fetching data from a service.

-@if (forecasts == null) -{ -

Loading...

-} -else -{ - - - - - - - - - - - - - - - - - - - -
DateTemp. (C)Temp. (F)Summary
@forecast.Date.ToShortDateString()@forecast.TemperatureC@forecast.TemperatureF@forecast.Summary
-} + + +

Loading...

+
+ + + + + + + + + + + + + + + + + + + + +
DateTemp. (C)Temp. (F)Summary
@forecast.Date.ToShortDateString()@forecast.TemperatureC@forecast.TemperatureF@forecast.Summary
+
+ + + + + + + + + + + + + + + + + + + + + +
IndexDateTemp. (C)Temp. (F)Summary
@item.Index@item.Value.Date.ToShortDateString()@item.Value.TemperatureC@item.Value.TemperatureF@item.Value.Summary
+
+
@code { - private WeatherForecast[] forecasts; + private WeatherForecast[] forecasts; - protected override async Task OnInitializedAsync() - { - forecasts = await ForecastService.GetForecastAsync(DateTime.Now); - } + protected override async Task OnInitializedAsync() + { + forecasts = await ForecastService.GetForecastAsync(DateTime.Now); + } }