Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - How to call ts function from js code and pass variable value

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.

Below is my code:

**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">.......

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a reference to HTML

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

Then

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...