Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 feeding data back to `<template>` from `[ngTemplateOutlet]`

Tags:

angular

So I have a component with a <template>

<some-component [data]="someArray">
  <template>foo<template>
</some-component>

and it's using this to get hold of the template

@ContentChild(TemplateRef)
public tmpl: TemplateRef<any>;

which is then used in its template like this

<div *ngFor="let item of someArrayFromDataInput">
  <template [ngTemplateOutlet]="tmpl"></template>
</div>

now I would like to be able to print some data from item in the original template, basically to be able to do this

<some-component [data]="someArray">
  <template>foo {{ item }}<template>
</some-component>

is it possible somehow?

like image 371
fxck Avatar asked Jun 06 '16 09:06

fxck


People also ask

What is * ngTemplateOutlet?

ngTemplateOutlet is a powerful tool for creating customisable components. It is used by many Angular libraries to enable users to provide custom templates.

What is the difference between ng-template and Ng-container?

ng-container serves as a container for elements which can also accept structural directives but is not rendered to the DOM, while ng-template allows you to create template content that is not rendered until you specifically (conditionally or directly) add it to the DOM.

Can we use ng-template inside ng-template?

ng-template is an Angular element that is used for rendering HTML in a template. However, it is not rendered directly on DOM. If you include an ng-template tag to a template, the tag and the content inside it will be replaced by comment upon render.

What is ng-template in stack overflow?

As the name suggests the <ng-template> is a template element that Angular uses with structural directives ( *ngIf , *ngFor , [ngSwitch] and custom directives).


1 Answers

Updated to match Angular 5+ api ngOutletContext was renamed to ngTemplateOutletContext as per https://stackoverflow.com/a/37654077/301596


Once this lands https://github.com/angular/angular/pull/9042 it will work like this

<div *ngFor="let item of someArrayFromDataInput">
  <template 
    [ngTemplateOutletContext]="{
      item: item
    }" 
    [ngTemplateOutlet]="tmpl"></template>
</div>

+

<some-component [data]="someArray">
  <template let-item="item">foo {{ item }}<template>
</some-component>

// edit: landed

like image 199
fxck Avatar answered Oct 13 '22 21:10

fxck