2

I am trying to create a table that uses a different ng-template for certain cells, depending on some data in the cell. (In this case, if the cell is in the "Entity" column, I want a template that shows a photo as well as the regular data.)

Using *ngIf I'm easily able to switch the ng-template in the table. But when I'm in the switched template, I no longer know how to access the cell data which is coming from the surrounding ngFor loop.

The template input variable is called "cell".

I thought I could pass cell to the new template using let-value="cell" but it doesn't work. Inside the template, the variable "value" is undefined. I also checked to see if "cell" is in scope without me even using a let-, but it's not, either.

How do I access the "cell" template input variable inside the various ng-templates that I swap in with the *ngIf?

<table>
  <tr *ngFor="let row of tableArray">
    <td *ngFor="let cell of row">
      <ng-container *ngIf="cell.column === 'Entity' then photoTemplate else cellTemplate"></ng-container>
    </td>
  </tr>
</table>

<ng-template #cellTemplate let-value="cell">
  {{value.display}} <<<==========DOESN'T WORK
</ng-template>

<ng-template #photoTemplate>
  {{cell.display}} <<<======= DOESN'T WORK EITHER WITHOUT THE let-
</ng-template>

Sorry for the newbie question. I come from AngularJS and Angular 5 is very new to me. I've searched the docs but I can't find anything.

thanks

John

PS This is a slight variation on the suggested duplicate because I'm trying to use dynamic templates with ngIf, which is a complication others may encounter, but not discussed in the duplicate.

In the end though the approach is the same. I had to abandon ngIf and use references to templates. (See below).

Though I note, following the answer in the suggested duplicate didn't work for me: I had to pass the context variable as a key value pair context:{cell:cell} rather than just as context:cell.

John
  • 5,581
  • 6
  • 29
  • 46
  • Possible duplicate of [Pass variable in Angular 2 template](https://stackoverflow.com/questions/43726749/pass-variable-in-angular-2-template) – Mateusz Witkowski Nov 29 '17 at 10:03

1 Answers1

3

You can use ngTemplateOutletContext to send data to template. See This link

Ankit Kapoor
  • 1,615
  • 12
  • 18
  • 1
    That did it, thanks. I wasn't able to figure out how to add ngTemplateOutletContext to an ngIf, so instead I added a template reference to each cell's data, and called it rather than using an ngIf. So instead of this `` I have this `` and then I catch the value in the template like this `` – John Nov 29 '17 at 22:08