Angular html 怎么调用 js中的函数
时间: 2024-02-01 19:14:42 浏览: 35
在 Angular 中,可以通过以下几种方式来调用 JavaScript 函数:
1. 在 HTML 模板中使用事件绑定调用函数:
```
<button (click)="myFunction()">Click me</button>
```
2. 在组件类中定义一个公共函数,并在 HTML 模板中调用:
```
@Component({
selector: 'app-my-component',
template: '<button (click)="myFunction()">Click me</button>'
})
export class MyComponent {
myFunction() {
// your code here
}
}
```
3. 在 HTML 模板中使用 Angular 内置指令 `ng-click` 调用函数:
```
<button ng-click="myFunction()">Click me</button>
```
但是需要注意的是,如果你要在 Angular 中调用外部 JavaScript 函数,你需要在组件类中声明该函数,并在 `ngOnInit()` 生命周期钩子函数中引入外部 JavaScript 文件,例如:
```
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component',
template: '<button (click)="myFunction()">Click me</button>'
})
export class MyComponent implements OnInit {
ngOnInit() {
const script = document.createElement('script');
script.src = 'path/to/your/external/js/file.js';
document.body.appendChild(script);
}
myFunction() {
// your code here
// call your external function here
}
}
```
这样就可以在 Angular 中调用外部 JavaScript 函数了。