Kevin Grabher
Kevin Grabher

Reputation: 399

Attach onclick to HTML received from API

I have a page that receives it's HTML-Contents from an API.

In that code there are DIVs with the class "openMap". When the user clicks on those DIVs I want a function to be executed (alert('yes') in the example below).

I have tried the following but while the

console.log(elementsWithClass[i]);

does output the HTML of each element, I can not add a click-event.

How can this be achieved? Current code:

this.http.get(httpGetUrl)
        .subscribe(data => {
            let returnedHtml = data['_body'];
            if(returnedHtml != ''){
                this.notdienstHtml = returnedHtml;
                this.zone.run(() => {
                    let elementsWithClass = document.getElementsByClassName("openMap");
                    setTimeout(function(){
                        console.log(elementsWithClass.length);
                        for (let i=0; i < elementsWithClass.length; i++) {
                            console.log(elementsWithClass[i]); //correctly outputs HTML-content of each DIV it iterates over
                            elementsWithClass[i].onclick = function(){
                                //not run when DIV is clicked
                                alert('yes');
                            }
                        };
                    }, 300);
                });
            }
        });

Upvotes: 0

Views: 199

Answers (2)

Kevin Grabher
Kevin Grabher

Reputation: 399

This is what I ended up with. Important thing is, if the content is dynamic, update it via element.innerHtml in the ts-file not with [innerHtml] in the html-file.

in the HTML

<div #mainHtml id="mainHtml"></div>

before the constructor:

@ViewChild('mainHtml') mainHtml: ElementRef;

function:

this.http.get(httpGetUrl)
        .subscribe(data => {
            let returnedHtml = data['_body'];
            if(returnedHtml != ''){
                let nativEl = this.mainHtml.nativeElement;
                nativEl.innerHTML = returnedHtml; //update the HTML
                let elements = nativEl.querySelectorAll('.openMap'); //openMap is the css selector
                for(let element of elements){
                    element.addEventListener('click', this.openMap.bind(this)); //openMap is the function name
                }
            }
        });

Upvotes: 0

Ashraful Islam
Ashraful Islam

Reputation: 1263

Try to bind the event from the component where the response will rendered.

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

constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  this.elementRef.nativeElement.querySelector('my-element')
                                .addEventListener('click', this.onClick.bind(this));
}

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

Upvotes: 1

Related Questions