Using @ViewChild and AfterViewInit to access the nativeElement of a component

Note: While my question may seem similar to others, the specifics are different.

I am attempting to execute a function on an element that is contained within a <ng-template>. Due to the fact that it is not rendered in the DOM, I am encountering difficulties. Upon researching, I discovered that it is feasible to use ViewChild. Here is my attempt:

HTML:

<ng-template #Payment>
  <input type="text" id="price">
</ng-template>

My approach to accessing the #Payment component is as follows:

@ViewChild('Payment', {read: ElementRef}) Payment: ElementRef;

Subsequently, my attempt to implement the function goes like this:

ngAfterViewInit() {
  this.Payment.nativeElement.querySelector('#price').addEventListener("keyup", function() {
    mask(this);
  });
}

Unfortunately, I am encountering the following error:

ERROR TypeError: this.Payment.nativeElement.querySelector is not a function

Now, my question is: how can I successfully apply this function to the element?

The objective is to apply a mask to this input field, which is housed within a modal inside <ng-template>. It should be noted that the function works as expected when the input is not contained within <ng-template>.

Answer №1

As mentioned in the resource https://angular.io/api/core/ng-template#description :

The ng-template element in Angular defines a template that remains hidden by default.

Therefore, accessing elements within <ng-template> is not possible until the template is rendered, either directly or indirectly in your scenario.

It's important to note that the nativeElement of <ng-template> is not a standard HTMLElement, so using querySelector will not yield the desired results. Instead, consider using nextElementSibling.

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

Configuring ESLint, Prettier, and TypeScript in React Native: A Step-by-Step Guide

Could you provide guidance on setting up ESLint, Prettier, and TypeScript in React Native? I'm currently using absolute paths to specify components. Can you confirm if this setup is correct? tsconfig { "extends": "@tsconfig/react-n ...

Looking for an Ionic 3 search function to filter a JSON array?

I am currently developing a market app using ionic 3, and one of the key features is the "products" list. Instead of manually inputting data, my "products page" retrieves items from a JSON array through an HTTP post request: postProducts(type){ return th ...

The services generated by OpenAPI Generator typescript-angular are experiencing failures

While utilizing version 2.4.26 of this OpenApi generator ("@openapitools/openapi-generator-cli": "^2.4.26"), I am encountering issues with Angular services (Angular Version 13.2.0). For example, the services are passing too many arguments to the Angular Ht ...

Are you interested in creating dynamic tables/models with Sequelize?

Currently, I am exploring a theoretical question before diving into the implementation phase. The scenario is as follows: In my application, users have the ability to upload structured data such as Excel, CSV files, and more. Based on specific requirement ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...

Limit input to numbers only in Semantic UI React Form Field

I've developed a custom CurrencyInput React component for users to input numeric values. I set the input type to "number", but unfortunately, this only seems to function properly in Chrome (as Firefox still allows non-numeric entries). Here is the co ...

Displaying grouped arrays efficiently in Angular

I have received data from an API in the form of an array with objects structured like so: [ {"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1}, ...

Retrieve a collection of Firestore documents based on an array of unique identifiers

I have a Firestore collection where one of the values is an array of document IDs. My goal is to retrieve all items in the collection as well as all documents stored within the array of IDs. Here is the structure of my collection: https://i.sstatic.net/rA8 ...

Facing issue with Angular 17 where pipe is displaying empty data

I am currently utilizing Angular 17 with the code provided below: database.component.html @for(user of (users | userPipe:filters); track user.id) { <tr id="{{ user.id }}"> <td>{{ user.name }}</td> <td> ...

Is it possible to stop the Angular application from loading/bootstrapping depending on the URL, Controller, or View?

My setup consists of ASP.Net MVC/Web API working alongside an Angular 2 application, with the exception of the login process which uses a traditional MVC view and controller. While everything functions correctly when loading the login page, the console is ...

issue with lazy loading Angular module containing a preview component

Greetings everyone! I successfully created an Angular app with lazy loading, but I encountered an issue when trying to open child pages inside modules. Instead of opening within the main page, it redirects me to a new page. Here is my module structure: co ...

Closing the side navigation bar when a router link is clicked on small devices

In my project, I have implemented the side-nav component for routing between different components. Here is how it looks: https://i.stack.imgur.com/v6hE8.png However, I am currently facing an issue with the side-nav. On mobile devices, the side-nav appear ...

What is the best way to eliminate tasks from a list in Angular?

I have been working on a scheduler tool that allows me to record the tasks I complete within a specific timeframe. These tasks are displayed in a list similar to a to-do list. One of the challenges I'm facing is removing individual items from the lis ...

The Angular CLI release does not match the Angular version

After updating Angular to version 9, my previously smoothly running angular project started throwing this error: This peculiar error message popped up: This version of CLI is only compatible with Angular versions 0.0.0 || ^10.0.0-beta || >=10.0.0 <1 ...

RXJS Subject data remains stale upon page refresh

A specific service I developed includes a subject titled selectedNode. My goal is to update the subject's value when providing a direct URL for page loading. Unfortunately, there seems to be an issue with updating the value of Subject directly via the ...

Leverage local JSON file data in HTML using TypeScript and Angular 7 for enhanced functionality

I am looking to incorporate a basic local JSON file into my Angular 7 project and utilize the data within my HTML file. Just a straightforward example. The JSON file is named data.json. I aim to retrieve the information from this JSON file in app.component ...

Error message: The function _this.$(...).modal is not defined for the OpaqueToken jQuery in Angular-cli

I'm facing an issue with using jQuery in Angular2. I can't seem to get my modal to pop out. Error message: I used Angular-cli npm install and then yarn to install bootstrap + In my .angular-cli.json file, I have the following scripts: "script ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

Error: An unauthorized attempt was made to modify property settings for certain users, which are designated as read-only

Within my Ionic app, there exists a specific page where users have the ability to modify information related to a particular city. What I aim to achieve is for these modifications to only be visible to other users who are also located within the same "City ...

Is there a method for verifying the application signature in Ionic?

For the past 2 days, I've been on a quest to find information about app certificate validation libraries/functions in Ionic. After discovering SignatureCheck.java for Android (link: enter link description here), I wonder if there is a similar solution ...