如何从js代码调用ts函数并传递变量值 [英] How to call ts function from js code and pass variable value

查看:1690
本文介绍了如何从js代码调用ts函数并传递变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这种情况,在单击html元素时,我正在使用jquery在home.ts中获取属性的值.当单击按钮时,我想调用一个函数,并将此获取的属性的值传递给被调用函数中的变量.

I have this situation where on clicking the html element i am fetching value of attribute in home.ts using jquery. When the button is clicked,I want to call a function and pass this fetched attribute's value in a variable in the called function.

下面是我的代码:

**home.html**

<div id="mainDiv">
  <span action="10004">Quick Task</span>
</div>

**home.ts**

//declare var $: any;
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import $ from "jquery"; //intentional use of jQuery

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController) {

  }

  actionid;

  ngOnInit(){
    var mainDiv = document.getElementById("mainDiv");
    mainDiv.addEventListener("click", function (event) {
      console.log("Inside Event Listener");
      event.preventDefault();
        var link_id = $(event.target).attr("action");
        console.log("Actionid is:: " + link_id);
      //  this.actionid = link_id;
      //  var x = this.callpagedata();
  });
  }

  callpagedata(){
console.log("callpagedata function fired,actionid is::", this.actionid)
  }

}

编辑

需要使用类似的东西:

Edit

Something like this needs to be used:

this.actionid = HTMLElement.addEventListener<"click">.......

推荐答案

添加对HTML的引用

<div id="mainDiv" #divRef>
  <span action="10004" #spanRef (click)="callAMethod($event)">Quick Task</span>
</div>

然后

从TS文件(组件)获取引用:

get Reference from TS file (component):

@Comp..
...
export class HomePage {
  @ViewChild('divRef') divReference: ElementRef;
  @ViewChild('spanRef') spanReference: ElementRef;
  public action=null;

  callAMethod(){
     this.action = this.spanReference.attr('action')
  }
}

这篇关于如何从js代码调用ts函数并传递变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆