在 angular 中从 jquery 调用 TypeScript 方法 2

Call TypeScript Method from jquery in angular 2

我在 angular 2 个表单中使用 boostrap-select 下拉菜单 jquery。 Onchange jquery 事件我想调用 Typescript onDropDownChangeChange 方法。但它不起作用。

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


}

你混淆了作用域。应该是这样的:

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

           }); 

    }); 
}

您缺少上下文。

并且要处理第 3 方库自定义事件,在某些情况下,您需要在收到这样的事件后告诉 Angular 运行 您的代码。

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

  }