Here’s the steps to getting a Blazor Component’s code out of a @Code
block and into it’s own file.
It doesn’t take much to make a one-file blazor component hard to work with since there’s markup and logic in the same file.
Let’s call our example component ExampleComponent.razor
.
ExampleComponent.razor
, add a file ExampleComponent.razor.cs
. Visual Studio should nest it appropriately.ExampleComponent
to ExampleComponentBase
and have that class inherit from Microsoft.AspNetCore.Components.ComponentBase
.@code
block into the body of the ExampleComponentBase
class.ExampleComponent.razor
, add @inherits ExampleComponentBase
before the @page
directive.@inherits
directive in a Razor page, add an [Inject]
Attribute and a {get;set;}
to injected dependencies. For example, @inject NavigationManager NavigationManager
in a Razor Component would become [Inject] NavigationManager NavigationManager { get; set; }
in a code-behind.private
fields accessed by markup to protected
. They will need to be protected
instead of private
since the Razor Component markup is now a sub-class of ExampleComponentBase
and thus cannot access private fields.