简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM