Pass variable in Angular 2 template

Is there a way to pass variables into 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 to get a template to print namefrom foo?

+6
source share
3 answers

You need to do the following:

<div *ngFor="foo in foos">
   <ng-container *ngTemplateOutlet="inner; context:foo"></ng-container>
</div>

<ng-template #inner let-name="name">
   {{ name }}
</ng-template>
+23
source

But this does not work if the template is in another component. How do you pass the context object in such a scenario?

I added
@Input() itemTemplate: TemplateRef<any>;

in the component where I will use it, and in the template of this component I write something like this:

  <ng-container *ngTemplateOutlet="itemTemplate; context: item"></ng-container>

Template code on the component side:

<ng-template #dataRendererTpl let-data="data">
<div class="data">Hello, {{data.name}}</div>

Just pass the link to dataRendererTpl as the @Input () property to the component where you need it

0
source

In case you want to send the entire iterable object to the template, you can pass the array to the context as follows:

<ng-container *ngTemplateOutlet="inner; context:foos"></ng-container>

<ng-template #inner let-foos="values()">
   <div *ngFor="foo in foos">
      {{ foo.name }}
   </div>
</ng-template>
0
source

Source: https://habr.com/ru/post/1692037/


All Articles