【问题标题】:Call TypeScript Method from jquery in angular 2从 Angular 2 中的 jquery 调用 TypeScript 方法
【发布时间】:2017-10-07 18:06:42
【问题描述】:

我正在使用带有 jquery 的 Angular 2 形式的 boostrap-select Dropdown。 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);
   }


}

【问题讨论】:

  • 在您仍然可以使用 ngModel 和/或模板语法来实现这一点的同时,使用 jQuery 监听该事件有什么意义?
  • 一般规则 - 每次你想在 Angular/React/Vue 应用程序中使用 jQuery 时,都有 99.999% 的机会有更好的做事方式。

标签: angular typescript angular2-forms typescript2.0


【解决方案1】:

你错过了上下文。

为了处理 3rd 方库自定义事件,在某些情况下,您需要告诉 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();
      }); 
    });

  }

【讨论】:

    【解决方案2】:

    您混淆了范围。应该是这样的:

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

    【讨论】:

    • 你现在工作正常。 onDropDownChange 事件我根据下拉值填充 Grid。代码执行没有任何错误,但 Grid 没有加载。你能帮忙吗?
    • @PrabhuArumugam 我不了解网格,很抱歉:/如果这个问题得到解决,你可以问另一个问题。
    猜你喜欢
    • 2019-10-08
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-20
    • 2018-05-05
    相关资源
    最近更新 更多