[Fixed] Access template variable inside component

Issue

I ran into an issue with ng-template.

We are passing some parameters via ngTemplateOutletContext like below in a table component. We use different renderers for the cells depending on the type of data contained inside. Notice the cellvalue parameter as it is what I need.

<ng-container *ngIf="useCellRenderer(column, row)">
   <ng-template [ngTemplateOutlet]="column.renderer.templateref" [ngTemplateOutletContext]="{ cellvalue: row[column.attr], rowvalue:row }">
   </ng-template>
</ng-container>

The template of the component in charge of the rendering looks as follows:

<ng-template #templateRef let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  {{ getTraslateValue(cellvalue)}}
</ng-template>

The template is able to access the cellvalue parameter and call the function correctly, but I want to access the same parameter from the component’s TS and can’t seem to be able to do it.

What I’ve tried so far goes along the line of the following snippet

@ViewChild('templateRef', { read: TemplateRef })
  public templateref: TemplateRef<any>;

  ngAfterViewInit() {
    console.log('ngAfterViewInit', this.templateref.elementRef);
  }

But cellvalue is nowhere to be found in the console.log

Thanks in advance!

Solution

So @SebOlens has guided me to the solution with what he said. I ended creating a directive with exportAs. The directive is as follows:

TS

@Directive({ selector: '[exposeVariable]', exportAs: 'exposed' })
export class ExposeVariableDirective {
  @Input() variablesToExpose: any;
  }
}

It can be used in the template in the following way for example:

HTML

<ng-template #templateRef let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  <div exposeVariable [variablesToExpose]="{cellValue: cellvalue}" #exposedRef="exposed">
    {{ getTraslateValue(cellvalue)}}
  </div>
</ng-template>

And the cellvalue can be accessed from the component:

TS

@ViewChild('exposedRef') public directiveExposed: any;

In my case the directive inits after the AfterViewInit of the component, so if you try to initialise something you will have to either watch the value of the ViewChild variable or, in my case, I did a component activated with an ngIf and a exposed variable from the template so I could use the hooks from the new component.

Thanks again @SebOlens 🙂

Leave a Reply

(*) Required, Your email will not be published