首页 > 解决方案 > 在角度 7 中将单击事件与 css 类绑定

问题描述

有什么方法可以像我们以前使用 jquery 一样将 click 事件与 Angular 7 中的类名绑定?

在 jquery 我能够做到这一点

$('.my-class-name').on('click',function(){});

angular 7中是否有类似的标准方式?

标签: angular7event-binding

解决方案


您可以直接将点击事件添加到具有所需类的 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() {});
    
}

推荐阅读