Событие привязки клика с классом css в angular 7

Есть ли способ связать событие клика с именем класса в angular 7, как мы привыкли с jquery?

В jquery я смог это сделать

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

Есть ли что-то подобное стандартному способу в angular 7?


person Pawan Nogariya    schedule 22.02.2021    source источник


Ответы (1)


Вы можете напрямую добавить событие клика в тег 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() {});
    
}
person Srikar Phani Kumar Marti    schedule 26.02.2021