0

I need to transform html, adding load event on image and doing some work in this events.So i use pipe.

The problem is that the data process in the load event is not reflected on the displayed html.

I may have missed something, here's how I process.

In template, i add my pipe PipeArticleContentToHtml:

    <div class="articleContent" 
[innerHTML]="selectedArticle.content | PipeArticleContentToHtml"></div>

pipe:

    @Pipe({ name: 'PipeArticleContentToHtml' })
export class PipeArticleContentToHtml implements PipeTransform {
    transform(content: string) {

        let htmlContent = document.createElement('div');

        htmlContent.innerHTML = content;
        let arrayImg = htmlContent.getElementsByTagName('img'); 

        for (let i = 0; i < arrayImg.length; i++) {
            let img = arrayImg[i];

            if (img.src.indexOf('zzzzzz.com') > -1) > -1) {
                img.className = "contentHideImg";
                // this one work
            }
            else {
                img.addEventListener('load', () => {
                    img.className = "FullImg";
                    // this one does not work, className is not changed in the view
                });

                img.addEventListener('error', () => {
                    img.className = "contentHideImg";
                    // this one does not work
                });
            }
        }
        return htmlContent.outerHTML;
    }

The treatment in the load event is not present in the displayed html. I supose that the reference to the image is lost, as I return htmlContent.outerHTML to the view.

But I do not see how to fix this or another manner of doing. Can we return the html with the added events?

or how can i work directly with html in the view?

Thanks for your help.

JeromeXoo
  • 1,378
  • 14
  • 16
  • `innerHtml` only adds a string. Strings don't carry event handlers or stuff. You need a different approach to add HTML and event handlers. – Günter Zöchbauer Jun 08 '16 at 17:31
  • Thanks for your answer. can i do that with pipe? – JeromeXoo Jun 08 '16 at 17:34
  • I don't think so. You can't do it with `innerHTML` and no other binding way. Pipes can only be used for bindings. Either you wrap your HTML you want to add in a component and add it for example with http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 or you get a reference to `ElementRef`and add it imperatively like you do in the pipe. – Günter Zöchbauer Jun 08 '16 at 17:41
  • 1
    Thank a lot, a good way to solve this. – JeromeXoo Jun 08 '16 at 18:38

0 Answers0