Skip to content

Consider adding an Index to your Iterator #3

@kevonh

Description

@kevonh

We started down the path of doing things like you are doing, but came up with a slightly different approach for the Iterator and Iterations... Essentially, we tried to keep as much of the razor tags as close to C# as possible. This implementation breaks one thing I like better about yours... and that is you have direct access to the object in the loop. With the below method,, one must understand you have an Item as well as an Index.

public class ComponentContext<T> where T : ComponentBase
{
    public ComponentContext(T @component) => Component = @component;
    public T Component { get; set; }
}

public class ForEach<T> : ComponentBase
{
    [Parameter]
    public IEnumerable<T> Items { get; set; }
    [Parameter]
    public RenderFragment<ForEachContext<T>> ChildContent { get; set; }

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        var index = 0;
        foreach (var item in Items)
            builder?.AddContent(0, ChildContent(new ForEachContext<T>(this, item, index++)));
    }
}

public class ForEachContext<T> : ComponentContext<ForEach<T>>
{
    public ForEachContext(ForEach<T> component, T item, int index) : base(component)
    {
        Item = item;
        Index = index;
    }
    public T Item { get; }
    public int Index { get; }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions