goku_da_master
goku_da_master

Reputation: 4317

How can I pass a List<string> as a parameter to a child component in blazor?

Here's an example of what I'd like to do:

Parent Component

<MyChildComponent ParamList="{hello, world, this is great}"/>

Child Component

<ol>
    @foreach(string myParam in ParamList)
    {
        <li>@myParam</li>
    }
</ol>

@code {
[Parameter]
public List<string> ParamList {get;set;}
}

Expected Output

1. Hello
2. World
3. this is great

I feel like I'm doing something wrong since I can't find anything in blazor docs about doing this. I'm not referring to splatting.

Upvotes: 2

Views: 6786

Answers (2)

Henk Holterman
Henk Holterman

Reputation: 273681

It dependes on what notation you prefer. If you want to keep the using side clean you could use a simple string and process it inside the component:

<MyChildComponent ParamList="hello, world, this is great"/>

...

<ol>
    @foreach(string myParam in ParamList.Split(',') )
    {
        <li>@myParam</li>
    }
</ol>

and the parameter is a simple string

@code {
[Parameter]
public string ParamList {get;set;}
}

Upvotes: 1

enet
enet

Reputation: 45734

You can do it in a variety of ways. This is one:

MyChildComponent.razor

<ol>
@foreach (string myParam in ParamList)
{
    <li>@myParam</li>
}
</ol>

@code {
   [Parameter]
   public IReadOnlyList<string> ParamList { get; set; }
}

Usage

<MyChildComponent ParamList="list" />

@code{

List<string> list =  new List<string> {"hello", "world", "Angular is great"};
} 

Upvotes: 4

Related Questions