typescript 如何在angular 2/类型脚本中使用href调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46999648/
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-10-21 04:59:40  来源:igfitidea点击:

how to call a function using href in angular 2/ type script

htmlangulartypescript

提问by levi

i want to call a function in type script component from <a>tag using hreflike this:

我想从<a>标签中调用类型脚本组件中的函数,href如下所示:

  <a href="fun()" ></a>

Is it possible in some way? Note that i need only this way. Using a "click".event does not help in my case..

以某种方式可能吗?请注意,我只需要这种方式。使用“点击”。事件在我的情况下没有帮助..

I tried already this:

我已经尝试过这个:

<a href="javascript:fun()"> 

but it does not work.

但它不起作用。

thanks!

谢谢!

回答by Arun Kumaresh

you cannot call function in href use roleattribute and make <a>as button and call the function with (click)

您不能在 href 使用role属性中调用函数并制作<a>为按钮并使用(click)

<a role="button" (click)="func()"></a>

回答by N K

I know this is an old question. This worked for me on Angular 6 -

我知道这是一个老问题。这在 Angular 6 上对我有用 -

<a href="javascript:void(0);" (click)="getSampleCSV()">CSV Template</a>

回答by Jesse Moreland

Something I noticed when addressing a similar issue is that you can surround your function call with {{ }} to have angular actually call the function.

我在解决类似问题时注意到的一点是,您可以用 {{ }} 包围您的函数调用,以便 angular 实际调用该函数。

<a href={{"javascript:fun()}}"> </a>

In my particular problem, I was trying to generate a dynamic link based on other information so I did something like

在我的特定问题中,我试图根据其他信息生成动态链接,所以我做了类似的事情

html:

html:

<a href="{{generateCustomLink(data)}}" target="_blank"></a>

typescript:

打字稿:

generateCustomLink(data: any) : string {
    return 'http://www.google.com';
}