Bhavin
Bhavin

Reputation: 2168

Click event not working with dynamically generated Elements in Angular 5

My question is how can we enable click event of dynamically generated HTML element using ElementRef.

HTML Code which is dynamically appended.

<ul class="list-group" style="border-radius: 4px;">
    <div class="file_list_event">
    <li class="list-group-item">        
        <button (click)="save_event_btn_app()" class="btn btn-sm btn-danger  delete_file_event pull-right" type="button">
        <i class="fa fa-close"></i> Delete</button>
        </div>
    </li>                   
</ul>

li is dynamically generated after service call. So, I'm not able to Generate the click event because it's a dynamically generated element.

So, for that I tried below code.

import { AfterViewInit, Component, ElementRef} from '@angular/core';

constructor(private elementRef:ElementRef) {}


  this.elementRef.nativeElement.querySelector('.delete_file_event')
                                .addEventListener('click', this.save_event_btn_app.bind(this)); 
 // Above code I have added just after the append code.

save_event_btn_app(event) {
  console.log(event);
}

But still I got the same error that,

ERROR TypeError: Cannot read property 'addEventListener' of null

Note:- I'm not sharing the dynamic html generation code because it's not necessary here.

Upvotes: 1

Views: 2205

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222657

You can handle this error by adding a check that el is not null before adding an event listener,

let el =  this.elementRef.nativeElement.querySelector('.delete_file_event');
if(el){
  el.addEventListener('click', this.save_event_btn_app.bind(this));
}

However to see why it is null , you need to add your dynamic generation code

Upvotes: 3

Related Questions