Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a typescript method from your html button onclick event

Tags:

typescript

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.

like image 447
user3750290 Avatar asked Aug 07 '17 10:08

user3750290


1 Answers

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();
like image 200
Kokodoko Avatar answered Nov 07 '22 20:11

Kokodoko