1

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

It worked. Thank you brother for this very quick answer.
How can I add click event with parameter because it shows click but When I'm passing arguments its not getting value with argument.
what is the argument?
In Button click it's a argument with string save_event_btn_app('string'). Which is in Button from dynamically generate HTML.
@Bhavin : you store in property and used when function get fired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.