12

I am new to typescript. I have a query on how to call a method inside a .ts file from your .html page when u click a html button

.ts file

class AdminTS {
    public alertMessageTS() {
        alert("This is the test call!!!.");
    }
}

.html page

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>
        Sample TypeScript page
    </title>
    <script src="AdminTS.js"></script>
</head>
<body>
    <input type="button" value="Click" onclick ="getTrainingName(1)">
    </input>
</body>
</html>

I am getting a runtime exception saying getTrainingName is undefined.

user3750290
  • 125
  • 1
  • 1
  • 6

2 Answers2

36

getTrainingName() is never defined in your example code, perhaps you forgot to add that part?

I would suggest not using javascript at all in your html, instead use addEVentListener to add handlers to dom elements. Then all your application logic will be in *.ts files.

(Since you already work with typescript it makes even less sense to add inline js in html)

.html file

<input type="button" value="Click" id="coolbutton"></input>

.ts file

class AdminTS {
  constructor() {
    let btn = document.getElementById("coolbutton");
    btn.addEventListener("click", (e:Event) => this.getTrainingName(4));
  }
  getTrainingName(n:number){
     // button click handler
  }
}

// start the app
new AdminTS();
Kokodoko
  • 26,167
  • 33
  • 120
  • 197
0

I wanted this on WindowLoad (not a TS expert by any means)

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Typescript GRPC Client</title>
  </head>
  <body>
   <input type="button" value="Get Result" id="coolbutton"></input>
   <p id="showresulthere">Result will be shown here</p>
   <script src="main.js"></script>
  </body>
</html>

TS file

window.onload = () => {
  console.log('On Page Load');
  let btn = document.getElementById("coolbutton");
  var input = document.getElementById('showresulthere') as HTMLElement | null;
  if (input != null) {
    console.log(input.textContent);
    btn.addEventListener("click", (e: Event) => showResult(input));
  }else{
    console.log("input is null");
  }

 }

function showResult(input: HTMLElement) {

  if (input != null) {
    input.textContent = "Some data";
  } else {
    console.log("input is null");
  }
}
Alex Punnen
  • 5,287
  • 3
  • 59
  • 71