CSS transitions need a property to animate, and you need to change that property. Since there isn’t a height or opacity change in the rules, it can’t animate. The nested components that actually change in response to the data collection changing come in and out of the DOM which is a change.
So, you have a couple of options:
-
Set a
height
to your container and change that with C# so that it travels to the DOM and do a CSS animation on it. This is going to be tough – you need to somehow calculate how tall you want your container. -
Hide all the content for a bit, then
await Task.Delay(20);
to let it render, then show it again (a simple if-block) – that can let initial css animation do its work. The caveat is that you will do a lot of DOM changes, maybe lose data (so you maybe need to do some state management) and the screen will flicker badly. -
Do animations with JS – when you alter the collection, get the current content height (the parent must have some height set and maybe hidden overflow, there are a few ways to setup the container so you can get the actual content size), and use JS to animate to the new height. That’s the general way animations are done – with JS, when you need particular dimensions and settings.
-
Try toggling a class on the main wrapping element that will contain the desired animation (such as fade), something like the pseudocode below
<div class="my-card @AnimationClass">
. . .
</div>
@code{
string AnimationClass {get;set;} = string.Empty;
ObservableCollection<TItem> MyList {get;set;} = new ObservableCollection<TItem>();
void OnInitialized()
{
MyList.CollectionChanged += MyCollectionChangedHandler;
}
//I don't remember the exact syntax here, if it can't take a Task, use Task.Run in the body to do the async work
async Task MyCollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)
{
AnimationClass = "my-anination-class";
await InvokeAsync(StateHasChanged);
await Task.Delay(500); // about the time of your animation
AnimationClass = "";
}
void Dispose()
{
MyList.CollectionChanged -= MyCollectionChangedHandler;
}
}