How to bind event listener for rendered elements in Angular 2?

前端 未结 5 833
一整个雨季
一整个雨季 2020-12-02 10:16

How can I bind an event listener in rendered elements in Angular 2?

I am using Dragula drag and drop library. It creates dynamic HTML but my event is not bound to dy

5条回答
  •  借酒劲吻你
    2020-12-02 10:57

    If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.

    import { Component, OnInit, Renderer, ElementRef} from '@angular/core';
    
    constructor( elementRef: ElementRef, renderer: Renderer) {
        dragulaService.drop.subscribe((value) => {
          this.onDrop(value.slice(1));
        });
    }
    
    public onDrop(args) {
    
      let [e, el] = args;
    
      this.toggleClassComTitle(e,'checked');
    
    }
    
    
    public toggleClassComTitle(el: any, name: string) {
    
        el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {
    
          item.addEventListener('click', function(event) {
                  console.log("item-clicked");
    
           });
        });
    
    }
    

提交回复
热议问题