Blazor now seems to support some form of inheritance but there is no clear documentation around it abstract style components are possible.
For example lets say I want to be able to insert N number of <DynamicComponent>
elements on a page, I need to be able to know up front what props they expose and how to fill them.
So I want to ideally force anyone making a component of this type to always have fields like:
@code {
[Parameter] public abstract EventCallback OnSomeMandatoryEvent {get;}
[Parameter] public abstract ISomeInterface Data {get;}
}
This way I know for sure the components I am wanting to pull in will always expose the required properties the convention requires.
So is this use case supported?
2
Answers
For anyone else who comes here looking for information on abstract classes for Blazor you can do the following:
Then use it like so:
I struggled to find any docs out around this specifically so while the interfaces above in the answer are good sometimes an abstract class will be what you need as you can hook into the lifecycle methods there too, allowing you to create conventions at base layers.
Its also worth noting you can also use generics on the abstract classes and add it to the consuming component like so
@inherits CustomElementComponent<SomeType>
This is how to implement interfaces in components.
Here are two interfaces:
And three components – only two of which implement the interface:
And a test page: