Search code examples
htmlangularoverriding

Add (click) method to link in text block in Angular component


I have a small problem. I'm getting a text from the server with innerHtml which is inserted in Angular component. Inside of this text, there are possibly some links. Example text block looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<a href="some.link.com">Link<a/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 

Is there a way to insert a bind there a click action like this?

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<a href="some.link.com" (click)="methodName('http://domain.tld/page.html')">Link<a/>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Thanks.


Solution

  • If I get you right, you render html loaded from server with innerHtml, in this case you can't use Angular directives inside of this template. But you can add listeners with common JS (document.addEventListener) after content rendering.

    @Component({
      template: `<div #wrapper [innerHTML]="sanitizedHtml"></div>`
    }) class MyComp {
      @ViewChild('wrapper') wrapper: ElementRef<HTMLElement>;
    
      ngAfterViewInit() {
         const links = this.wrapper.nativeElement.querySelectorAll('a[href]');
         links.forEach(link => 
           link.addEventListener('click', this.linkClickHandler.bind(this));
         );
      }
    
      linkClickHandler(event: MouseEvent) {
        ...
      }
    }