aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Provide a way to reference child components

Open stavroskasidis opened this issue 8 years ago • 5 comments

Consider the following component usage

<ComponentWrapper>
     <MyComponent />
</ComponentWrapper>

Let's assume the components have the following code

MyComponent.cshtml

<input type='text' />

ComponentWrapper.cshtml

<div>
@ChildContent
</div>
@functions{
    RenderFragment ChildContent;
}

Is there a way (other than js interop) to get a reference to the child components in ComponentWrapper.cshtml? Is this on the "todo" list?

stavroskasidis avatar May 02 '18 09:05 stavroskasidis

If the child component (<MyComponent>) wishes to expose its <input> element, then it can capture an ElementRef to that element (new feature in 0.3.0) and expose it as a public property or could expose a method that returns it.

If the child component (<MyComponent>) does not wish to expose its own internal implementation details, then they are encapsulated and not accessible to the parent component.

So it's entirely up to you to choose what to expose. The new ref syntax in 0.3.0 lets you expose ElementRef if you want to :)

SteveSandersonMS avatar May 02 '18 10:05 SteveSandersonMS

Sorry, I probably didn't explain the question in detail, let me elaborate.

What I am referring to is having an Enumerable of all child components (e.g. MyComponent) in the ComponentWrapper component.

Following my previous example:

ComponentWrapper.cshtml

<div>
@ChildContent
</div>
@functions{
    RenderFragment ChildContent;
    
     void override OnInit()
     {
            foreach(var child in ChildComponents)  //Hypothetical property
            {
                Console.WriteLine("I have a : " + child.GetType().Name);
            }

            //This should print "I have a : MyComponent"
      }
}

Is this currently supported somehow and I missed it ?

stavroskasidis avatar May 02 '18 12:05 stavroskasidis

AFAIK, there is no way right now like in Angular ("ViewChildren") to get all children of some type. or enumerate children. "ref" matches up with Angular(ViewChild), but not array or list of them, it would be nice if it supports. for ex:

<TabComponent>
<Tab></Tab>
<Tab></Tab>
<Tab></Tab>
</TabComponent>

dlr1 avatar May 02 '18 12:05 dlr1

React also supports this

https://www.reactenlightenment.com/basic-react-components/6.8.html

stavroskasidis avatar May 02 '18 13:05 stavroskasidis

I see what you mean now. For Blazor this fits into the work we plan to do to enable templated components. Specifically, APIs for reading and writing the contents of a RenderFragment as a DOM.

SteveSandersonMS avatar May 02 '18 13:05 SteveSandersonMS