28
votes

I'm looking for solution to pass current component scope data into ng-content directive.

I've app-table component template with data I want to pass into child content, using some solution like this:

<!-- some html before -->
<table>
    <!-- complex header markup with sorting/filtering support -->

    <tr *ngFor="let item of data">
         <ng-content [value]="item"></ng-content> //how to pass data?
    </tr>
</table>
//some html after

And page template where I want to use this data:

<app-table>
     <td>{{value.Name}}</td>
     ...
</app-table>

Is this possible?

2
what about @Input? - toskv
I need ng-content as I have many other templates inside app-table, like empty table, etc - VadimB
I guess you're looking for ngForTemplate or NgTemplateOutlet stackoverflow.com/questions/39974126/… - yurzui
@VadimB have you found a solution to this? I am facing exactly same problem here - eddyP23
@yurzui, unfortunately no :( I had no time to dive deeper inspecting this problem. Also do not found any useful information regarding this feature on official documentation. - VadimB

2 Answers

11
votes

I think you could find your answer here: Angular 2 passing html to ng-content with bindings.

The ng-content component is badly documented, unfortunately. It will be soon, according to the Angular GitHub issue (https://github.com/angular/angular.io/issues/3099).

9
votes

I faced the same issue, for more clarification, I added your example working.

<!-- some html before -->
<table>
    <!-- complex header markup with sorting/filtering support -->

    <tr *ngFor="let item of data">
      <ng-template [ngTemplateOutlet]="templateRef" [ngTemplateOutletContext]="{$implicit: item}"></ng-template>
    </tr>
</table>
//some html after

In the Component, you need to declare templateRef like this.

export class AppTableComponent {
  ...
  @ContentChild(TemplateRef) templateRef: TemplateRef<any>;

  ...
}

Then you use your component like this.

<app-table>
 <ng-template let-item>
     <td>{{item.Name}}</td>
     ...
 </ng-template>
</app-table>