Angular2 - Do something when innerHTML changed

I have a component and its inner html is dynamically changing. I do some operation on the child DOM elements of this component, so I have to repeat the operations each time the inner html of this component is changed.

For example in the component:

myElements = this.el.nativeElement.querySelectorAll('.myClass');
// do something with that DOM elements

And in the view:

<div *ngFor="let item of myItems">
    <div class="myClass">...</div>
</div>

I have to call

myElements = this.el.nativeElement.querySelectorAll('.myClass');

Each time myItems is updated and new DOM elements loaded.

Can I bind the innerHTML to ngOnChange() or is there other ways to achieve this?

Upvotes: 1

Views: 2189

Answers (1)

chrispy
chrispy

Reputation: 3612

You could try ngDoCheck:

https://angular.io/docs/ts/latest/api/core/index/DoCheck-class.html

You would manually check the old value and the new value of the innerHtml, then execute your custom code.

Potential example:

public ngDoCheck(){
    if(this.oldInnerHtml != this.newInnerHtml){
        //take custom action
    }
}

Upvotes: 2

Related Questions