Angular 6 Click Event on document.getElementsByClassName live html Collection

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Angular 6 Click Event on document.getElementsByClassName live html Collection



I have a [innerHtml] that has several classes I want to add click events to:




...

inner = server.getInnerHtml();

ngAfterViewInit()
var els = document.getElementsByClassName("highlight"); //I want all the html elements with class ".highlight"
console.log(els.length); //its 0!!!
Array.from(els).forEach( el =>
console.log(el)
);
console.log(els); //this prints fine, i guess since live collection


<div [innerHtml]="inner | safeHtml"></div>



How do I add a click event listener to each element in the elements array once the live collection has loaded in Angular? Is there a way to do with by making the collection a observable?



Thanks





Try ngAfterViewInit instead of ngOnInit.
– ConnorsFan
Aug 12 at 14:07


ngAfterViewInit


ngOnInit





@ConnorsFan Whoops, I mean to put ngAfterViewInit. Doesn't work, i think because it takes time for the innerHtml to render, even after the view initializes.
– Jeremy Lee
Aug 12 at 14:15





I do not see any element with this class
– brk
Aug 12 at 14:21





@brk it is a element inside the innerHtml called "inner".
– Jeremy Lee
Aug 12 at 14:25





An alternative is to listen to click events on the document or on the window, and check if the event.target has the highlight class.
– ConnorsFan
Aug 12 at 15:17


event.target


highlight




1 Answer
1



Here is the stackblitz code that listens for click event for document.element that contains class name 'highlight'.



https://stackblitz.com/edit/angular-jgeapi





Thanks! This seems to work if I set a timeout for a second, but not right after the view initializes, since I am fetching data from my api. Is there anyway to check a specific div for changes then to run the code in your ngAfterVkewInit?
– Jeremy Lee
Aug 12 at 14:57






We can only catch asyncronous code using observable. Not possible to check whether DOM is changed or not. Please upvote it it is right
– Suresh Kumar Ariya
Aug 12 at 15:01






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard