0
votes

I've designed a simple blazor component which is a wrapper for a card. The usage looks like this:

<Card Title="Some title">
    <CardBody>My body content</CardBody>
    <CardFooter><a href="...">Go</a></CardFooter>
</Card>

It's pretty straightforward to use. However, in some cases, I do not wish to use the CardFooter component. But I cannot conditionally choose to render CardFooter. The If statement cannot be outside like this:

@if(myCondition){<CardFooter><a href="...">Go</a></CardFooter>};

It must be inside like this:

<CardFooter>@if(myCondition){...display something};</CardFooter>

The problem is I have to render an empty CardFooter regardless. I wish I could use the IF statement to decide not to render the footer at all. Is it possible?

Thanks!

2
Is the component the "Card" and you're trying to control the rendering inside "Card" component from outside, or do you have 3 different components? - Neil W

2 Answers

1
votes

If <CardBody> and <CardFooter> are subcomponents of <Card> then add a parameter on your <Card> component.

[Parameter] public bool ShowFooter { get; set; }

Then, from the host use:

<Card ShowFooter=@myCondition>

Then inside your <Card> component, use:

@if (ShowFooter)
{
    <CardFooter>Content</CardFooter>
}
2
votes

Two options. I do think the requirement that the conditional be inside the component while using 3 components sounds a bit....odd/forced...almost like a test. But if forced to go that route, make the condition a parameter of CardFooter:

So the card markup like this:

<Card>
    <CardBody>
        Something in the body
    </CardBody>
    <CardFooter Visisble="someCondition">
        Something in the body
    </CardFooter>
</Card>

The footer component like this:

@if (Visisble)
{
    <div class="card-footer">
                @ChildContent
    </div>
}

@code
{
    [Parameter]
    public RenderFragment? ChildContent { get; set; }   

    [Parameter]
    public bool Visisble {get;set;} = true;
}

Personally, for something as simple as a card, I would probably create a single component (Card) and use two templates (Body and Footer).

Then the markup would look a bit like:

<Card ShowFooter="true == false">
    <Body>Blah blah blah</Body>
    <Footer>
        <span>Footer</span>
    </Footer>
</Card>

@code
{
    [Parameter]
    public RenderFragment Body { get; set; }
    
    [Parameter]
    public RenderFragment Footer { get; set; }    

    [Parameter]
    public bool ShowFooter {get;set;} = true;
}

Going this route would allow you to make sure you CSS worked together.