Reputation: 394
I've tried to use this code in my .NET 5 Blazor project, in .razor file:
<SignedLabel class="some-css-class" Price=123 Currency=Currency.Usd />
where SignedLabel
- is a Blazor component and Price
, Currency
is the component's input parameters. I expect Blazor to treat the class
word as an html property and apply the plain HTML class to this component so that I can style this component later on. But Blazor actually treats it as another input parameter for component and crashes whole app rendering with error:
Object of type 'SignedLabel' does not have a property matching the name 'class'
So the questions is
PS: project settings:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>
<LangVersion>9</LangVersion>
</PropertyGroup>
...
</Project >
Upvotes: 3
Views: 2333
Reputation: 14553
You cannot apply a class to a Component. You can use splatting to capture attributes placed on a Component to pass as parameter to one of the components elements.
SomeComponent.razor
<div @attributes="@CapturedAttributes">
Hello
</div>
@code {
[Parameter(CaptureUnmatchedValues = true)]
public Dictionary<string,object> CapturedAttributes { get; set; }
}
<SomeComponent id="fred" class="some-css-class" style="width:100vh" />
<div id="fred" class="some-css-class" style="width:100vh" >
Hello
</div>
Upvotes: 19
Reputation: 782
I've encountered a similar issue and Google led me here, so I share it for anyone who might hit this as well.
My project setup is .NET 7 and Teams App project template (Blazor Server).
The problem was similar to OP's - I wanted to apply CSS class to Web Component. In my case it was FluentTextField
, so I couldn't modify its code.
Although doing this:
<FluentTextField
class="w-100"
Placeholder="Provide the URL"
Required="true"/>
wasn't producing any errors and in browser Dev Tools I could see the class added the element, i.e. <fluent-text-field class='w-100'>
, the CSS defined in parent component wasn't applied.
Turns out, it's enough to change "Blazor syntax" to "JS syntax" and everything works fine:
<fluent-text-field
class="w-100"
Placeholder="Provide the URL"
Required="true"/>
Upvotes: 0
Reputation:
You just have to create a Parameter in your component. For example, this works fine. In a Tree component, TopDivClass parameter has been added an used.
In the markup of the component:
<div class="@TopDivClass">
In the code behind of the component:
[Parameter]
public string TopDivClass { get; set; }
In the markup using the component:
<Components.Tree TopDivClass="TreeView" />
The result in the HTML is
<div class="TreeView" ...
Upvotes: 3