Problem when using RenderFragment

Posted 1 year ago by leoog5
0

Hi,

I would like some help. I have List of RenderFragments which I am using to show various data in my Blazor component. I am trying to add functionality to delete one element of the list on click of the button. After simple List.RemoveAt method wasn't working as expected I tried to delete whole list and repopulate it with RenderFragments but then component's OnInitializedAsync() method is not invoked. Am I correct in understanding that RenderFragment objects are still in the memory and they are just reused. Is there a way to delete them from memory after removing them from the list?

  • 0

    Here's a basic example of removing an item from a list. This is an index page. If you run this, you'll see the items remove from the list when you click the button.

    @page "/"
    
    @foreach (var item in _list)
    {
        <div>@item</div>
    }
    
    <p>
        @if (_list.Count == 0)
        {
            <div>All Items Removed. <b @onclick="SetList" style="cursor: pointer;">Reset</b></div>
        }
    </p>
    
    <button @onclick="RemoveItem">Remove</button>
    
    @code {
        private List<int> _list = new();
    
        protected override void OnInitialized()
        {
            SetList();
        }
    
        private void SetList()
        {
            _list = new List<int> { 10, 20, 30, 40, 50 };
            StateHasChanged();
        }
    
        private void RemoveItem()
        {
            var lastIndex = _list.Count - 1;
    
            if (lastIndex >= 0)
                _list.RemoveAt(lastIndex);
        }
    }
    Posted 1 year ago by selliott
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 0
An error has occurred. This application may no longer respond until reloaded. Reload 🗙