Search code examples
c#compiler-errorsblazor

How to disable (make an error) on ChildContent?


Consider this markup:

<MyComponent>
  This is ChildContent
</MyComponent>

It is all fine if MyComponent actually supports ChildContent, if not by default user/dev will be notified about this fact in runtime.

How to disable it, so it will become compile error?

Update, Github issue for this: https://github.com/dotnet/aspnetcore/issues/57391


Solution

  • To enforce that child content is not allowed at compile-time in a Blazor component, you can use the EditorRequired attribute on a required parameter. However, Blazor does not provide a built-in mechanism to prevent ChildContent at compile-time directly.

    Instead, you can leverage the absence of a ChildContent parameter in your component's definition to indirectly achieve this. If a component does not define a ChildContent parameter, attempting to use it will result in a compile-time error.

    Here's how you can design a component that does not support ChildContent: using Microsoft.AspNetCore.Components;