javascriptangularinnerhtmlmouseclick-event

Click event is not working in dynamically generated HTML from typescript


Please find my code and help me out if there is any mistake in my code.

Controller.ts

Generating dynamic HTML code:

    Maintitle = Maintitle + " " + "<a href='javascript:void(0);' id='code-links' (click)='clickLinks();'>" + item.code[0] + "</a>";



      ngAfterViewInit() {
           if (this.elementRef.nativeElement.querySelector('#code-links')) {
                this.elementRef.nativeElement.querySelector('#codelinks').addEventListener('click', this.clickLinks.bind(this));
                }
            }

Pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    @Pipe({
        name: 'safeHtml'
    })
    export class SafeHtmlPipe implements PipeTransform {
    constructor(private sanitized: DomSanitizer) { }
        transform(value) {
        return this.sanitized.bypassSecurityTrustHtml(value);
         }

    }

HTML:

     <ul class="list-group list-group-code subTerms">
                <li class="result-success list-group-item strong" *ngFor="let item of xmlTabularContentFinal">
                  <span class="text-muted font-weight-normal"><span> <span [innerHTML]="item.title| safeHtml"></span></span></span>
                </li>
              </ul>

While I inspect the elements I could see the event is binding in the html. But the event is not triggered when I click the link.


Solution

  • since ngAfterViewInit() method executes before the dynamic html could load the event binding was not working. Now I am having an explicit method to bind the event after html content loaded.

    Issue is been resolved and working with click event.