Skip to content

How to detect changes in a directive when innerHTML code is updated in angular?

I am testing a directive that is adding to divs, these are implementing innerHTML, the directive is in charge of highlingthing with a click on the div (changing the color), but I want to change when the component is updating the content in the innerHTL as well, the problem is that the ngOnChanges hook is not aware of any changes. How to handle this kind of changes in the directive? What is the event more appropiate to listen this changes? Is requiring a hostlistener?

Directive implementation:

<div appHighlight [innerHTML]="htmlStr"></div>

Onchanges in the directive

  selector: '[appHighlight]',
export class HighlightDirective implements OnInit, OnChanges {
  constructor(private el: ElementRef) { = 'yellow';

  ngOnChanges(changes) {
   console.log('ngOnChanges ---->');
   console.log(changes, 'changes are not dectected');

  ngOnInit() {
     console.log('ngOnInit ---->');

  @HostListener('click', ['$'])
  onClick(btn) {

  changeColor() { = 'magenta';

Stackblitz sample:

directive in div that is using innerHTML


Change detections happen when @input‘s are changing

this is probably not exactly what you want but its what you could do.

In your highlighed directive add an input:

htmlString: string; // this is the named you bind to -> [htmlString]

and and then apply the binding on the directive as well

<div appHighlight [htmlString]="htmlStr" [innerHTML]="htmlStr"></div>

then you will get updates. It will happen on initialization again later when you update the string.

edited strack: