我是 Angular 新手,我遇到了这个错误:
“openClose 未在 HTMLButtonElement.onclick (index:13) 处定义”
我搜索了所有可能的答案,但问题是错误出现在索引页面中,而不是任何应用程序文件中。 我将我的代码粘贴在这里,希望有人知道该怎么做。
app.component.html
<button id="btn1" class="btn1" onclick="openClose(this, 'bg-modal')">Click me </button>
<div class="bg-modal" id="bg-modal">
<div class="modal-content">
<div class="col-12">
<div class="close" id="close">+</div>
<h2>Modal</h2>
<hr>
</div>
<div class="col-12">
<div class="contents">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
</div>
<div class="confirm" id="confirm">OK</div>
</div>
</div>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css',
'./video-style.css']
})
export class AppComponent {}
function openClose(btn1, bgmodal){
document.getElementById('.btn1').addEventListener('click', function(){
document.getElementById('.bg-modal').style.display='flex';
});
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Modal</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
我试过了:
将 app.component.ts 中的代码放在 export class AppComponent {}
的括号之间
在index.html中只留下
将点击的代码放入 index.html 的标签中,然后它就可以使用 0 错误
谁能帮忙?
最佳答案
这是应该的。 :
<button id="btn1" class="btn1" (click)="openClose($event, 'bg-modal')">Click me </button>
在 Component.ts 文件中。 :
public openClose(event, bgmodal){
.... rest of code
}
注意:Angular 不建议直接访问 DOM 元素。
只是为了让您的场景正常工作,添加一个 Stackblitz 演示:Demo
关于javascript - 函数未在 HTMLButtonElement.onclick Angular 4 中定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864106/