【问题标题】:How to call ts function from js code and pass variable value如何从js代码调用ts函数并传递变量值
【发布时间】:2018-09-16 20:11:00
【问题描述】:

我有这种情况,在单击 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&lt;"click"&gt;.......

【问题讨论】:

  • 你能绑定一个事件(即onclick)到你的HTML吗? - 我认为您应该阅读有关 Angular 事件绑定的信息。它将为您节省 ngOnInit(...) 函数中的所有丑陋代码,并弃用使用 jQuery(至少对于此用例)的需要 -> 这是一个关于绑定点击事件的简洁教程:talkingdotnet.com/how-to-bind-click-event-angular-2
  • 我很清楚,但是有一些需要以这种方式获取值,我需要获取动态给出的操作 ID 并将其传递给函数
  • 我明白了...你能用好旧的&lt;span action="10004" onclick=callpagedata(this)&gt;Quick Task&lt;/span&gt;吗?
  • 给我 action 属性的值,如果我可以在像 this.actionid 这样的变量中获取它,那么一切都会奏效
  • 必须使用这样的东西this.actionid = HTMLElement.addEventListener&lt;"click"&gt;.......

标签: javascript jquery angular typescript ionic-framework


【解决方案1】:

添加对 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')
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2017-07-23
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多