How to access a template variable within a component

I encountered a problem with ng-template.

In our table component, we pass parameters using ngTemplateOutletContext as shown below. Depending on the data type, we use different renderers for the cells. Pay attention to the cellvalue parameter, it is crucial for my needs.

<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 within the rendering component appears like this:

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

Although the template can access the cellvalue parameter and function correctly, I am struggling to access the same parameter from the TS component.

I have attempted the following snippet so far:

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

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

However, the cellvalue does not appear in the console.log.

Thank you in advance!

Answer №1

With guidance from @SebOlens, I found the solution by creating a directive with exportAs. Here is the directive code:

TypeScript

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

This directive can be used in a template like this:

HTML

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

The cellvalue can then be accessed from the component using:

TypeScript

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

In my case, the directive initializes after the AfterViewInit of the component. To handle this, you can either watch the value of the ViewChild variable or use a temporary component activated with an ngIf and an exposed variable from the template to utilize the hooks of the new component.

Thank you once again @SebOlens :)

Answer №2

Just a friendly suggestion, not necessarily an answer. Please don't penalize if it doesn't solve the issue.

Have you considered attempting something like this?

html

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

ts

@ViewChild('cellValue') public cellValue: any;

I'm uncertain about its success as constructions like #cellValue="cellvalue" typically require directives with an exportAs descriptor in their decorators.

This approach won't function:

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

It targets the template itself rather than the dynamically generated portion of the DOM. You may want to try referencing the specific DOM element generated by the template instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React/Redux encountered a roadblock when attempting to iterate through an array stored in the state

Currently, I am delving into the world of React/Redux and have encountered a stumbling block while transitioning one of my single-page web applications to this framework. What I aim to achieve is to populate an array in the initial state of the web app wit ...

Is it possible to obtain the output of a JavaScript file directly? (kind of like AJAX)

My previous experience with AJAX involved a server-side language like PHP generating xHTML with attached JS. The JS would then query another file using parameters set in either GET or POST. The output of the queried file would be returned to the JS, which ...

Extract a section of the table

I'm looking to copy an HTML table to the clipboard, but I only want to include the rows and not the header row. Here is the structure of the table: <table style="width:100%" #table> <tr> <th class="border"></th> ...

Import resolves Uncaught ReferenceError by preventing access to 'xx' before it is initialized

Currently, I am troubleshooting a peculiar error that has come up. Within my service file where all other services are stored, I have included the import of one component along with all the other services required by the frontend. import { VacationComponen ...

Exploring the implementation of JavaScript bit-shift and bit-wise operations in Java

I'm currently attempting to emulate the functionality of JavaScript bit-shift and bitwise operations in Java. Have you ever tried to accomplish this task, and how can it be done reliably and consistently even when dealing with long integers? var i ...

Rearrange component positions without triggering a re-render

I am currently developing a React page for a chat application with a UI design similar to the image provided (Please disregard the black box for sensor info). https://i.sstatic.net/ErVN8.png Within this page, I have created two separate components: The ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

Reveal concealed fields following the selection of a specific option

I'm looking to create a bookmarklet that will automatically fill in values when clicked. Currently, I can select values using: document.getElementById('component').value="IAE-Data Agent"; document.getElementById('component').onch ...

Guide on updating a variable to the following string within an array

Snippet: months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October&apos ...

Using ASP.NET MVC, pass a list of values separated by commas to an action method

Hey there, I'm facing an issue with an ajax call where I am trying to retrieve values from an html select multiple tag. The problem arises when I attempt to pass these values into my controller as I keep getting a null reference error in my controller ...

Adjust the height of a CSS div to automatically fit the space between two other divs

I am trying to adjust the height of my table (with class "body") so it automatically fits the remaining space between the header div and the footer div. All three divs are enclosed within a fixed and centered position on the screen. Update: JSFiddle w ...

Identified the category

How can I retrieve the default option from a list of options? type export type Unpacked<T> = T extends Array<infer U> ? U : T; interface getDefaultValue?: <T extends Option[]>(options: T) => Unpacked<T>; Example const options = ...

Issue with jQuery 'on' event not triggering following 'load' event

I am facing an issue on a page where similar events occur but when new content is loaded halfway through, most of the jQuery functionalities stop working. The scenario involves answering questions in a 'game' format using AJAX calls. Once all que ...

Unleashing the power of plugins and custom configurations in your next.js next.config.js

const optimizeNext = require('next-compose-plugins'); const imageOptimization = require('next-optimized-images'); const config = { target: 'serverless', }; module.exports = optimizeNext([imageOptimization], config); tra ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

Transmit a base64-encoded image in an HTTP request to the server

I am currently working on sending a base64 image using the request npm module from a nodejs/express application to another REST API endpoint. Below is the code I am using: First, I have middleware set up using multer and datauri to upload the image in mem ...

Enhancing UI design with Vue.js

I'm attempting to customize elements using data from a JSON file in Vue.js: <div v-for="(item, index) in json._items" class="help-inner-callout" v-html="item.text" style="top:item.top; left: item.left;">&l ...

When the enter key is pressed, shift the text to a different input field

I am facing a complex requirement How can I detect the pressing of the ENTER key within a text box with the following conditions: If the cursor is at the end of a sentence, it should create a new text box on the next row. If the cursor is in the middle ...

Display various divs simultaneously based on the quantity of items in the dropdown menu

In my project, there is a dynamic select list that retrieves items from the database. Users have the ability to add or delete items from this list. Below is some code related to this functionality: <div class="form-group col-md-3"> <la ...