Encountering TypeError when invoking a Typescript function from Jquery in Angular 2

I'm currently working on a component that has an input text field with an attached input event listener using JQuery. My goal is to call a Typescript function when the input value changes, but unfortunately I keep encountering an uncaught TypeError.

Below is the code snippet in question:

import {Component, Input, Output, EventEmitter, ElementRef, OnInit} from 'angular2/core';
declare var jQuery: any;

@Component({
    selector: 'setting-priority',
    template: '<input [(ngModel)]="priority" class="setting-priority" type="text">'
})

export class SettingPriorityComponent implements OnInit{
    @Input() priority: number;
    @Output() prioChanged: EventEmitter<number> = new EventEmitter();

    constructor(private elementRef:ElementRef) { }

    ngOnInit() {
        jQuery(this.elementRef.nativeElement).find('input').on('input', function() {
            // Call the onChange function when input value changes
            this.onChange();
        });
    }

    ngOnChanges(changes) { 
        this.prioChanged.emit(this.priority);
    }

    // Update the priority variable with the received value
    onChange() {
        console.log("onchange!");
    }
}

The reason for using Jquery in this scenario is because the input value will be set programmatically - which causes Angular's Change Detection mechanism to not work correctly Additional details here

However, whenever the input event is triggered, it results in an Uncaught TypeError: this.onChange is not a function

Can someone please point out what mistake I might be making?

Answer №2

It's recommended to steer clear of using jQuery when working with Angular2.

An alternative Angular-inspired method for obtaining a reference to an element is shown below:

@Component({
    selector: 'setting-priority',
    template: '<input #prio [(ngModel)]="priority" class="setting-priority" type="text">'
})
export class SettingPriorityComponent implements OnInit{
  @ViewChild('prio') priority;

  ngOnInit() {
    console.log(this.priority);
  }
}

And if you need to add an event handler, all you have to do is:

template: '<input [(ngModel)]="priority" (input)="onChange()" class="setting-priority" type="text">'

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

no results returned from server request

The information variable is not returning the expected values of "OK" or "EXISTS". I've implemented a template with an overlay effect in income.html. The template includes a form and a button labeled "Add a new category". When the button is clicked, ...

When using jQuery's .appendTo method, the .text function may return an empty value for the

I have implemented a select box plugin from to modify a select box. For example, you can view it here: http://jsfiddle.net/ukkpower/bczrc/1/ The issue I am facing is with getting text from 'a' tags. There are two types of these 'a' t ...

Identify the specific child element that has been clicked on

I am interested in capturing the user-selected values for my element. Within my variable var1, here are the options: <select> <option value='1'>1</option> <option value='2'>2</option> <option ...

The loaded iframe did not deliver any valid message

Need some assistance with the following issue. Hello Ray, I have noticed that responses are coming back correctly for IE7/8 immediately. However, Firefox takes its time to upload with a progress bar indicating the process. I'm concerned that someone ...

The jQuery slideToggle animation causes navigation elements to shift unexpectedly

Hey there! I've been working on creating a drop-down menu using jQuery and I've encountered an issue. When I click on a navigation element, the other elements seem to drop about 20px. Any idea what might be causing this? Your help would be greatl ...

What is the most effective method for retrieving a particular object from an array of objects in AngularJS?

As I develop a service that contains an array of dynamic objects, I want to grant any controller the ability to access a particular object within this array. Is it necessary for me to use a for loop to locate the desired object? Are there more efficient m ...

How can I set up a pop-up to appear every 10 minutes on my asp.net website?

I am attempting to create a popup that opens every 10 minutes and automatically closes within 15 seconds. The code below shows a popup that currently only opens on click, but I want it to open automatically every 10 minutes. <script type="text/javascr ...

What is the best way to manage variables and locate the parent record within knockout nested arrays paging?

My current setup involves an observable array with another array as one of its elements, allowing me to create a "twisty" format with tables. Whenever an element is clicked, an ajax statement is triggered to populate the child array. My dilemma lies in i ...

Find the initial occurrence of this element using AngularJS

Here's my query: In angular, how can I scan through JSON to locate the first occurrence of isPrimary:true and trigger a function with the corresponding GUID? I have a webservice that provides JSON data for available Accounts including display names a ...

Delete the click event listener that was previously assigned by a different script

After extensive investigation using the Chrome developer tools, I have identified a click event listener that needs to be removed: https://i.sstatic.net/dnB3Q.png I successfully removed the listener using the developer tools. Further analysis revealed th ...

Building a dynamic web application using JDBC Template, AngularJS, and RESTful APIs

Seeking guidance on populating an HTML table with data from an MS SQL Database. I have configured my app.properties for the sql server and initialized my jdbcTemplate in my .java file. As a newcomer to AngularJS and jdbcTemplate, any example code or pointe ...

Stop the automatic display of the dropdown menu

How can I prevent the dropdown menu from automatically showing when I remove the 'hidden' class in jQuery: Sample HTML: <div class="btn-group btn-group-xs friend-request tooltiped" data-toggle="tooltip" title="Add as friend"> <button ...

How can I set the default option of a dropdown menu to "Choose an option"?

When setting up my dropdown menu, the default option is blank. Is there a way to change this text to something else? <body ng-controller="controller"> <span>Options: </span> <select ng-options="item as ...

Error encountered in Azure Pipelines build task: Failure due to requirement for initialization

When I directly invoke index.js using node, everything works fine. However, when running the Mocha tests, the task fails with a "Must initialize" error message. This is how my tasks index.ts code looks like: import * as path from "path"; import tl = requ ...

Angular 4 Web Application with Node-Red for Sending HTTP GET Requests

I am creating a unique service that utilizes Node-red to send emails only when a GET request is made to 127.0.0.1:1880/hello (node-red port), and an Angular 4 web app (127.0.0.1:3000) for client access. Upon accessing the /hello page from a browser, I rec ...

EventEmitter's Emit function failing to dispatch data to listeners

Currently, I am in the process of establishing a connection between two components using a service: LoaderComponent and AppComponent with LoaderService. The goal is to display a loader whenever the application fetches data. However, when attempting to util ...

What is the best method for extracting data from the Firebase realtime database in Ionic 3?

I have successfully incorporated the Firebase Realtime Database into my Ionic 3 application. As of now, I can perform the basic Create, Retrieve, Update, and Delete operations directly on my real-time database. However, I am looking to query the retrieved ...

Is it possible to enforce a certain set of parameters without including mandatory alias names?

My inquiry pertains to handling required parameters when an alias is satisfied, which may seem complex initially. To illustrate this concept, let's consider a practical scenario. If we refer to the Bing Maps API - REST documentation for "Common Param ...

What is the best way to utilize the features of component A within component B when they exist as separate entities

Component A has all the necessary functionalities, and I want to use it in Component B. The code for ComponentA.ts is extensive, but it's not written in a service. How can I utilize the logic from Component A without using a service, considering both ...

Error: Emit was called before the Angular Webpack plugin was initialized while running npm start

An issue arises: Attempted emission before initialization of Angular Webpack plugin. Error: Failed to start Angular compilation - The Angular Compiler needs TypeScript version >=5.2.0 and <5.3.0, but it found 5.4.5 instead. ** The Angular Live Deve ...