How to Invoke a TypeScript Function in Angular 2 Using jQuery

Using the Bootstrap-select dropdown in Angular 2 forms with jQuery, I am attempting to call a Typescript method called onDropDownChangeChange on the onchange event. However, it seems to not be functioning as expected.

import { Component, OnInit, ViewChild } from '@angular/core';
import { RequestOptions } from '@angular/http';
import 'rxjs/add/observable/throw';
declare var $: JQueryStatic;

export class TestComponent implements OnInit {
  selectedValue: string;

  ngOnInit(): void {

        $(function() {
         var self = this;
          $('.selectpicker').on('change', function(){
            var selectedds = $(this).find('option:selected').val();
            self.onDropDownChangeChange(selectedds); //This is not working
            //this.onChange();
          });

        });  

  }

  onDropDownChangeChange(value: string) {
        this.selectedValue = value;
        this.PopulateGrid(selectedValue);
   }


}

Answer №1

Your understanding of scopes seems a bit confused. Here's the correct way to approach it:

ngOnInit(): void {

    var self = this;
    $(function() {
        
          $('.selectpicker').on('change', function(){

              var selectedOption = $(this).find('option:selected').val();
              self.onDropDownItemSelected(selectedOption); //This line needs fixing
              //this.triggerChange();

           }); 

    }); 
}

Answer №2

The missing piece here is the context.

To properly handle custom events from a third party library in Angular, there are cases where you need to ensure that your code runs only after receiving the event. Here is an example of how you can achieve this:

constructor(private ngZone: NgZone) {}
ngOnInit(): void {
    let self = this;
    this.ngZone.run(() => {
      $('.selectpicker').on('change', function(){
        let selectedValue = $(this).find('option:selected').val();
        self.onDropDownChange(selectedValue);
        // perform any other actions related to the change event
      }); 
    });

  }

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

Intercepting Nested Requests in a Nest.js Application

Can you explain how to incorporate a nested interceptor in Nest.js? I currently have two interceptors: UsersInterceptor and PostsInterceptor UsersInterceptor: @Injectable() export class UsersInterceptor<T> implements NestInterceptor<T, Response& ...

When accessing from the frontend (Angular), the User.FindFirst(ClaimTypes.NameIdentifier) method does not return any values

I'm encountering a new issue - just as the title suggests. I've managed to identify where the problem occurs but I'm unable to resolve it. Let's start from the beginning. In the backend (ASP.NET 3.0), I have a class AuthController with ...

Explore the intricacies of RxJS catchError

I am a beginner in RxJS and I am struggling to understand how the parameters are passed in this code snippet: import { catchError, map, Observable, of } from 'rxjs'; let obs$ = of(1,2,3,4,5); obs$.pipe( map(n => { if (n === 4) { ...

Tips for sorting queries within a collection view in Mongoose:

I am working with Mongoose and creating a view on a collection. NewSchema.createCollection({ viewOn: originalModel.collection.collectionName, pipeline: [ { $project: keep.reduce((a, v) => ({ ...a, [v]: 1 }), {}), }, ], ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

The Angular2 module x.module does not contain the exported member NavComponent

Encountering difficulties with rc.5 of Angular2. I have created an NgModule named xModule where I define NavComponent and export it. This is specified in the file x.module.ts. However, when attempting to import xModule into yModule and export NavComponent ...

I am unable to run ng serve at the moment

Every time I enter ng serve it shows: Your global Angular CLI version (10.0.1) is higher than your local version (6.2.9). The local Angular CLI version will be used. To prevent this warning, use ng config -g cli.warnings.versionMismatch false. Schema va ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

How Angular 2's change detection system causes unnecessary DOM refreshing

My application is currently in the live beta stage and I am focused on improving its performance. One issue that has caught my attention is the flickering of images within a table. Upon investigation, I discovered that the DOM is continuously refreshing, e ...

What is the best way to retrieve the elements within a third-party selector?

Within the same package, I am working with a selector called "own date picker." This selector includes a "div" element that contains an "input" field. I need to modify the CSS of this input field, but cannot directly access it in my project because it is p ...

Converting a string to the Date class type in Angular 4: A comprehensive guide

Within my .ts file, I have a string that looks like this: const date = "5/03/2018"; I am looking to convert it into the default date format returned by Angular's Date class: Tue Apr 03 2018 20:20:12 GMT+0530 (India Standard Time) I attempted to do ...

Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name. The function in question is as follows: isOrganic() { for (let i = 0; i < this.items.length; i++) { if(this.ite ...

Trigger an error in TypeScript with an embedded inner error

Is it possible to throw an Error with an inner Error in TypeScript, similar to how it's done in C#? In C#, you can achieve this by catching the exception and throwing a new one with the original exception as its inner exception: try { var a = 3; ...

I am struggling to set up angular-localstorage4

I have been following the instructions in the provided link: angular-localstorage4 When attempting to import WebStorageModule and LocalStorageService from angular-localstorage, I encounter an error in the console even though the compilation is successful. ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

Cordova Emulate Android cannot locate Gradle or an installed Android Studio, despite their presence

Error Message After taking a break from the project and returning to it, I encountered an error message that I couldn't resolve no matter what solution I tried. Seeking help here as I know the app itself should be functioning properly. If you are un ...

Error message TS2339 in Typescript: The property '__super__' is not found on the type '($element: any, options: any) => any'

Having trouble with Javascript code inside typescript. $.fn.select2.amd.require([ 'select2/data/array', 'select2/utils' ], function (ArrayData, Utils) { /* tslint:disable */ function CustomData ($element, opti ...

Creating a sortable and filterable table in NG-ZORRO using Ant Design

I am currently facing an issue with implementing filters and sorters for all columns in my application, which uses the ng-zorro-antd table component. The challenge arises because the table data is dynamic. Please refer to the snippet of my current code be ...

What is the best way to store an audio Blob in the repository file system?

Currently, I have set up a system to record user audio through the device's microphone and can successfully download it on the same device. However, my goal now is to store this audio in my database by making an API call. How can I efficiently send th ...