如何从js代码调用ts函数并传递变量值

时间:2018-04-06 18:20:32

标签: javascript jquery angular typescript ionic-framework

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

以下是我的代码:

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

}

修改

需要使用类似的东西:

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

1 个答案:

答案 0 :(得分:0)

添加对HTML的引用

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

然后

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

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

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