Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass scope data into ng-content in Angular2

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?

like image 297
VadimB Avatar asked Jan 06 '17 16:01

VadimB


People also ask

How do you pass data into Angular components?

There are two ways to pass data into a component, with 'property binding' and 'event binding'. In Angular, data and event change detection happens top-down from parent to children. However for Angular events we can use the DOM event mental model where events flow bottom-up from child to parent.

Can we style ng-content?

Use the :host /deep/ selector. If you want to use the shadow DOM polyfill and style your components using the style or styleUrls attribute of the Component decorator, select the element with :host , then ignore the shadow DOM polyfill with the /deep/ child selector. :host will select the element.


2 Answers

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).

like image 141
DotBert Avatar answered Sep 25 '22 04:09

DotBert


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> 
like image 30
emanuel Avatar answered Sep 24 '22 04:09

emanuel