See how little code it takes to build a Battleships game in Blazor.
This article will show you an example of how list items can be implemented and made dynamic using components. In the end, you will have a simple user list, where you can edit emails and remove the items.
Since then this is a joined project, of API, class library, and client-side blazor, we will have to look at API and the shared class library at the same time. As this is where the data comes from.
Throughout the application, we only use two models - one for user data and one for their bank data.
For test data, we simply have a couple of static lists, in a FakeDatabase class.
For the data to be retrieved, we need a couple of controllers - GetUsers and GetBankDetailsForUser methods.
For the updates, we have two more action methods: DeleteUser and UpdateEmailAsync. The first one removes the user in the fake database list and the second one updates the email.
For the client-side, we simply have to retrieve and display the values. There is no logic, except for the visual changes.
The main procedures will occur in the list item component. The user data is retrieved on the parent page, but the bank details we retrieve once the user parameter is set. Other than that, the data is properly displayed in the appropriate fields. The fields are actually part of a table, basically, the component is a single row for the table.
Getting to the interesting part, you can see how smooth the whole editing approach is. We only need a boolean value and two different arrangements for what the user can see. They will either see a button and the value, or an edit field and a button. Once the first button is clicked, the boolean is_editoropened is set to true and therefore the editing view opens up. Then, once the "Done" button is clicked, the application simply sends an API request to make the change and displays it.
You may also see that we have an event callback for the removal of an item. That will be handled in the parent page, as the item displayed come from a list in the parent page.
For the main page, we first have the main table. Remember, the component is a row of a table and in the main part of the table, we generate components using a foreach loop. We have a users list, which contains user data that is passed into each component. We retrieve the items when the page is loaded, so there is really nothing fancy about that. The more interesting part here is the RemoveItem method, which takes the user data and invokes an API call to remove it from our fake database. Once that is done, it simply removes the item from the list, the loop for rows gets re-evaluated and you do not see that item anymore.
As you can see, between the main page and the component, we have quite a few lines of code. So, if nothing else, components will make it more readable.