Is it possible to specify two different type param values for parent and child components in Blazor?

Viewed 186

Please refer the following code blocks. For that code blocks, I have tried to access the parent component values into child component, but it always return the null value in child component.

<Parent TValue="TreeData">
 <Child TValue="TreeNode<TreeData>"></Child>
</Parent>

@code {
    public class TreeData
    {
        public string Value { get; set; }
    }
    public class TreeNode<TreeData>
    {
        public int Count { get; set; }
    }
}

**Parent Component:**

<CascadingValue Value="@this">
    @ChildContent
</CascadingValue>

**Child Component:** 

@code {
    [CascadingParameter]
    private Parent<TValue> ParentObj { get; set; }
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        //Parent obj always returns the null value
        ParentObj?.UpdateChildProperties("UpdateData", this);
    }    
}
1 Answers

Some general things to consider:

  1. Make sure your child component (or your _Imports.razor) has a using statement for that namespace.
  2. The [CascadingParameter] in the child must be public.
  3. Make the type of the [CascadingParameter] the name of the parent (without the.razor)
  4. If you have multiple different types you want to pass as a cascading parameter that's fine, just make another [CascadingParameter] in the child.
  5. If they need to use the same [CascadingParameter] in the child component then all those types that are being passed down must inherit from the same class (.razor). This .razor can be empty just make sure to include @inherits (whatever your base type is) and make the type of the [CascadingParameter] in the child the type of the base and in the on initialize you can check for type and cast it if needed.

I believe doing these things should fix this issue but as Curtis mentioned in the comment - it is difficult to follow this code with the way it is separated.

Related