Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable in Angular 2 template

Tags:

Is there a way I can pass variables to templates in Angular2?

Let's say I have the following code:

<div *ngFor="foo in foos">     <ng-container *ngTemplateOutlet="inner"</ng-container> </div>  ---------------  <ng-template #inner>     {{ foo.name }} </ng-template> 

How can I get the template to print the name of foo?

like image 476
alexandernst Avatar asked May 01 '17 21:05

alexandernst


People also ask

How do I pass a template reference variable in component?

To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .

What is template variable in Angular?

Template variables help you use data from one part of a template in another part of the template. Use template variables to perform tasks such as respond to user input or finely tune your application's forms. A template variable can refer to the following: a DOM element within a template. a directive or component.


2 Answers

You should do like this:

<div *ngFor="foo in foos">    <ng-container *ngTemplateOutlet="inner; context:foo"></ng-container> </div>  <ng-template #inner let-name="name">    {{ name }} </ng-template> 
like image 193
Tommy Thong Nguyen Avatar answered Sep 21 '22 15:09

Tommy Thong Nguyen


in my case I needed the object to remain intact because I had some kind of recursion, this worked

<div *ngFor="foo in foos">    <ng-container *ngTemplateOutlet="inner; context: {foo : foo}"></ng-container> </div>  <ng-template #inner let-foo="foo">    {{ foo.attributexy }} </ng-template> 
like image 43
Kisinga Avatar answered Sep 25 '22 15:09

Kisinga