Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call TypeScript Method from jquery in angular 2

Im using boostrap-select Dropdown in angular 2 forms with jquery. Onchange jquery event i want to call a Typescript onDropDownChangeChange method. But its not working.

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);
   }


}
like image 707
Prabhu Arumugam Avatar asked May 09 '17 12:05

Prabhu Arumugam


2 Answers

You are confusing the scopes. It should be like this:

ngOnInit(): void {

    var self = this;
    $(function() {

          $('.selectpicker').on('change', function(){

              var selectedds = $(this).find('option:selected').val();
              self.onDropDownChangeChange(selectedds); //This is not working
              //this.onChange();

           }); 

    }); 
}
like image 113
eko Avatar answered Nov 02 '22 03:11

eko


You're missing the context.

And to handle 3rd party library custom event, in some case you need tell Angular run your code after received the event like this.

constructor(private zone: NgZone) {}
ngOnInit(): void {
    var self = this;
    this.zone.run(() => {
      $('.selectpicker').on('change', function(){
        var selectedds = $(this).find('option:selected').val();
        self.onDropDownChangeChange(selectedds);
        //this.onChange();
      }); 
    });

  }
like image 28
Tiep Phan Avatar answered Nov 02 '22 04:11

Tiep Phan