函数未在 HTMLButtonElement.onclick Angular 4 中定义

我是 Angular 新手,遇到以下错误:


“openClose 未在 HTMLButtonElement.onclick (index:13) 中定义”


我搜索了所有可能的答案,但问题是错误出现在索引页面中,而不是出现在任何应用程序文件中。我将在这里粘贴我的代码,希望有人知道该怎么做。


应用程序组件.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>

应用程序组件.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';

    });

}

索引.html


<!doctype html>

<html>

<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 中的代码放在导出类 AppComponent {} 的括号之间

  • 在index.html中只留下

  • 将点击代码放入index.html 中的标签中,然后它会出现 0 错误

有人可以帮忙吗?


德玛西亚99
浏览 65回答 3
3回答

有只小跳蛙

事情应该是这样的。:<button&nbsp;id="btn1"&nbsp;class="btn1"&nbsp;(click)="openClose($event,&nbsp;'bg-modal')">Click&nbsp;me&nbsp;</button>在 Component.ts 文件中。:public&nbsp;openClose(event,&nbsp;bgmodal){ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;....&nbsp;rest&nbsp;of&nbsp;code&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;}请注意:在 Angular 中不建议直接访问 DOM 元素。只是为了让您的场景正常工作,添加 Stackblitz 演示:演示

慕桂英4014372

onclickat按钮不能调用组件的函数,必须用javascript代码调用,例如:onclick="console.log('sss')"如果你想调用组件的功能:.html:<button id="btn1" class="btn1" (click)="openClose(this, 'bg-modal')">Click me </button>.ts:import { Component } from '@angular/core';@Component({&nbsp; selector: 'app-root',&nbsp; templateUrl: './app.component.html',&nbsp; styleUrls: ['./app.component.css',&nbsp; './video-style.css']})export class AppComponent {&nbsp; &nbsp; openClose(btn1, bgmodal){&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('.btn1').addEventListener('click', function(){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById('.bg-modal').style.display='flex';&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }}

呼啦一阵风

如果您使用 Angular,您应该提及您想要使用哪个事件。如果你想使用点击事件那么你应该这样使用:<button&nbsp;(click)="onSave()">Save</button>因为角度没有任何类似的事件单击时
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5