Last active
August 3, 2021 02:42
-
-
Save fredgdaley2/dc843147026673eeb9263c2aced026fe to your computer and use it in GitHub Desktop.
Blazor Component - ListView includes ConditionalDisplay and ForEach components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@typeparam TItem | |
<ConditionalDisplay Show="@Render"> | |
@HeaderTitle | |
<ul> | |
<ForEach Items="@Items" Context="item"> | |
<ItemTemplate> | |
@ItemTemplate(item) | |
</ItemTemplate> | |
</ForEach> | |
</ul> | |
</ConditionalDisplay> | |
@code { | |
[Parameter] | |
public bool Render { get; set; } | |
[Parameter] | |
public RenderFragment HeaderTitle { get; set; } | |
[Parameter] | |
public RenderFragment<TItem> ItemTemplate { get; set; } | |
[Parameter] | |
public IReadOnlyList<TItem> Items { get; set; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@page "/" | |
@inject TodoStateProvider TodoState | |
@inject IJSRuntime JSRuntime | |
@implements IDisposable | |
<input @ref="newToDoItem" type="text" id="newItem" @bind="newItemText" /> | |
<button @onclick="@AddItem">Add Item</button> | |
<button @onclick="@RemoveCheckedItems">Clear Completed</button> | |
<ListTodos Title="Todo Items" TodoState="@TodoState" /> | |
<ListTodos Title="Completed Todo Items" TodoState="@TodoState" ShowCompleted="true" /> | |
<ListView Items="@TodoState.TodoItems" Render="@TodoState.TodoItems.Any(i => i.IsDone)"> | |
<HeaderTitle> | |
<h5>Display Completed Todos</h5> | |
</HeaderTitle> | |
<ItemTemplate> | |
<ConditionalDisplay Show="@context.IsDone"> | |
<li style="list-style:none" @key="@context.Title"><label for="@context.Title">@context.Title</label> <input type="checkbox" id="@context.Title" @bind="@context.IsDone" /></li> | |
</ConditionalDisplay> | |
</ItemTemplate> | |
</ListView> | |
@code { | |
string newItemText { get; set; } | |
private ElementRef newToDoItem; | |
protected override void OnInit() | |
{ | |
// subscribe to the objects OnChangeEvent | |
// Fire StateHasChanged to notify component that state has changed to rerender for updates. | |
TodoState.OnChange += StateHasChanged; | |
} | |
async void AddItem() | |
{ | |
TodoState.Add(new TodoItem { Title = newItemText }); | |
newItemText = ""; | |
await newToDoItem.Focus(JSRuntime); | |
} | |
void RemoveCheckedItems() | |
{ | |
TodoState.ClearCheckedItems(); | |
} | |
void IDisposable.Dispose() | |
{ | |
TodoState.OnChange -= StateHasChanged; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment