如何在单击按钮时使用 TypeScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25152463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:30:33  来源:igfitidea点击:

How to use TypeScript on a button click

typescript

提问by Himanshu Porwal

I am trying to use typescript in my application. for the same I am doing an POC and in POC i want to call a function Defined in TypeScript class on button click.

我正在尝试在我的应用程序中使用打字稿。同样,我正在做一个 POC,在 POC 中,我想在单击按钮时调用在 TypeScript 类中定义的函数。

Is it possible to call the function? If yes then how?

可以调用函数吗?如果是,那么如何?

So far I have seen examples where the functions are called on Page load only. I need to call a function on certain event.

到目前为止,我已经看到了仅在页面加载时调用函数的示例。我需要在某个事件上调用一个函数。

Thanks.

谢谢。

采纳答案by basarat

I need to call a function on certain event.

我需要在某个事件上调用一个函数。

If the function is global e.g. TypeScript:

如果函数是全局的,例如 TypeScript:

function foo(){
   alert('foo');
}

Just use onclicke.g. html:

只需使用onclick例如 html:

<button onclick="foo()">click me!</button>

Remember TypeScript is(almost) JavaScript.

记住打字稿(几乎)的JavaScript。

However I recommend using a framework like angular with TypeScript. For maintainability. As an example take a look at : http://youtu.be/Km0DpfX5ZxM

但是,我建议在 TypeScript 中使用像 angular 这样的框架。为了可维护性。作为一个例子看看:http: //youtu.be/Km0DpfX5ZxM

回答by sunny rai

HTML WILL BE:

HTML 将是:

<button (click)="myMethod($event)">Click Event</button>

function in .ts file

.ts 文件中的函数

private myMethod(event:any):void
{
   alert(JSON.stringify(event));
}