angular7 - 在角度 7 中将单击事件与 css 类绑定
问题描述
有什么方法可以像我们以前使用 jquery 一样将 click 事件与 Angular 7 中的类名绑定?
在 jquery 我能够做到这一点
$('.my-class-name').on('click',function(){});
angular 7中是否有类似的标准方式?
解决方案
您可以直接将点击事件添加到具有所需类的 HTML 标记中
In your case:
****** Method 1 ******
lets say you are writing the above className on a button, then
<button class="my-class-name" (click)="yourFunction($event)">
Your button
</button>
If you want to add it from the TS File only, then you can use the following method:
*** Method 2 ******
**STEP 1:**
// Create a view child template reference
@viewChild('someName', {static: false})
private someNameVC: ElementRef
**STEP 2:**
// Add this 'someName' to the HTML Element in .html FIle
<button class="my-class-name" #someName>
Your button
</button>
**STEP 3:**
// In your component.ts file, whenever you want to add the event listener, create a function and do the following :
yourMainFunction() {
if (someCondition) {
this.addEventListenerToButtonMethod();
......rest of the code
}
}
addEventListenerToButtonMethod() {
const parentElement: HTMLElement =
this.someNameVC.nativeElement.parentNode as HTMLElement;
// Here you can add your event listener
parentElement.addEventListener('click', function() {});
}
推荐阅读
- javascript - 查找数组中的中间元素
- javascript - 如何在 AngularJs 中从 HTML 转换 JavaScript 代码
- java - 删除动态模式中的特殊字符
- gis - 为两个不同的场景运行从同一个补丁初始化海龟
- python - 使用 value_counts() 从数据框中获取最高值
- java - java - 如何在java中对由Class对象组成的hashmap作为键和另一个hashmap作为值进行排序?
- angular - 来自 chokidar (C:\) 的错误:错误:EBUSY:资源繁忙或锁定,使用任何代码将 PDF 转换为图像时 lstat 'C:\DumpStack.log.tmp'
- python - 如何在 Python 中停止 Firebase 数据库的 listen() 方法?
- python - 在 Python CI/CD 中强制执行类型提示
- c++ - 从外部数据源更新 QAbstractItemModel