在没有点击事件的情况下在 HTML 中调用 TypeScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38380212/
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
Call TypeScript function in HTML without a click event
提问by Roka545
I know how to call a TypeScript when clicking a button, but how do you call a function without that type of event? I would like to call a function when I have an array called chartData populated. This is what I have:
我知道如何在单击按钮时调用 TypeScript,但是如何在没有该类型事件的情况下调用函数?当我填充了一个名为 chartData 的数组时,我想调用一个函数。这就是我所拥有的:
<div *ngIf="chartData.length">
chartMethod();
</div>
But instead of chartMethod()
being called, it just prints 'chartMethod()' on the html page.
但它没有chartMethod()
被调用,而是在 html 页面上打印“chartMethod()”。
I've also tried:
我也试过:
<script>
chartTest();
</script>
but the function was still not called.
但该函数仍未被调用。
回答by Reginaldo Camargo Ribeiro
It happens because this chartTest()
is incapsulated by Angular and is not accessible outside Angular.
But inside angular you can, you just need to:
发生这种情况是因为这chartTest()
是由 Angular 封装的,并且在 Angular 之外无法访问。但是在 angular 里面你可以,你只需要:
<div *ngIf="chartData.length">
{{chartMethod()}}
</div>
But it will add an undefined in html so just test
但它会在 html 中添加一个 undefined 所以只是测试
<div *ngIf="chartData.length">
{{chartMethod() ? chartMethod() : ""}}
</div>
But I don't think it's html resposibillity call any method, it needs to be done by the component itself in typescript.
但我不认为它是 html resposibillity 调用任何方法,它需要由组件本身在打字稿中完成。
回答by RAHUL KUMAR
Angular 2, You can call a method automatically by passing a method 'checkFieldAccess()' in [ngClass]In template file write this
Angular 2,您可以通过在[ngClass]中传递一个方法'checkFieldAccess()'来自动调用一个方法 在模板文件中写这个
[ngClass]="{check:checkFieldAccess(dataPass)}"
回答by BrunoFigueiredo
In your component.ts put his after constructor
在你的 component.ts 中放置他的构造函数
ngAfterViewInit(){
this.getUser();//Put here your function or what you need
}
ngAfterViewInit() is called after a component's view, and its children's views, are created. Its a lifecycle hook that is called after a component's view has been fully initialized.
ngAfterViewInit() 在组件视图及其子视图创建后调用。它是一个生命周期钩子,在组件的视图完全初始化后调用。