Angular ng-content: how to use parents data as children input

Viewed 857

I have a component that uses <ng-content></ng-content>, and this component has itself some data that should be passed to whatever component goes inside the <ng-content></ng-content> tags.

Component that uses ngContent:

parent.component.ts

class ParentComponent {
    data;
}

parent.component.html

<p>Data:</p>
<ng-content><ng-content>

Component that should go inside Component that uses ngContent:

child.component.ts

class ChildComponent {
    // I need this to be passed from parent component
    @Input() data; 
}

child.component.html

<ul>
    <li *ngFor="let element of data">{{ element.name }}</li>
</ul>

Desired usage:

view.component.html

<parent-component>
    <child-component [data]="data"></child-component>
</parent-component>

Is there a way to have the child-component's input [data] come from parent-component? I have tried this approach in a personal project, but I get an empty list, somehow is not been passed.

1 Answers

A solution closest to your desired usage would be achieved through the use of template reference variables:

<parent-component #parent>
  <child-component [data]="parent.data"></child-component>
</parent-component>
Related