Skip to content
Advertisement

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

@Directive({
  selector: '[appHighlight]',
})
export class HighlightDirective implements OnInit, OnChanges {
  constructor(private el: ElementRef) {
     this.el.nativeElement.style.backgroundColor = 'yellow';
  }

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

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

  @HostListener('click', ['$event.target'])
  onClick(btn) {
      this.changeColor();
  }

  changeColor() {
    this.el.nativeElement.style.backgroundColor = 'magenta';
  }
}

Stackblitz sample:

directive in div that is using innerHTML

Advertisement

Answer

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:

@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: https://stackblitz.com/edit/angular-ivy-xvr116?file=src%2Fapp%2Fdirectives%2Fhighlight.directive.ts

Advertisement