0

Is it possible to bind to an event which is from external content. Content is brought in via innerHTML

I have the below code whereby I grab external content and display it within my app. I'm trying to listen to an onClick event for the <a> tag. The <a> is a route redirect. The listen should reside within my app as I want do some other things before routing to a new route.

I've tried setting a handleClick function but I don't think this is the correct way to do it.

I also thought maybe using a ElementRef - in this case #view but would jquery light be better in this case.

@Component({
  selector: 'overview-details',
  template: `
    <h2>{{ title }}</h2>
    <div #view [innerHTML]="regCode | sanitizeHtml"></div>
  `
})

ngOninit() {
    this.regcode = `
        <div>
            <h1>RegCode Content</h1>
            <a class="link" (click)="handleClick()">Link</a>
        </div>
    `;
}

//within controller
handleClick(){
    // do some stuff
    // then route
    router.navigate([somewhere....]);
}

2 Answers 2

1

Angular doesn't process HTML added with [innerHTML]="..." or any other way. Bindings like (click)="..." work only when added statically to a comopnents template.

You can use

constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  this.elRef.nativeElement.querySelector('a.link').addEventListener('click', this.handleClick.bind(this));
}
Sign up to request clarification or add additional context in comments.

Comments

1

I worked out the following in the end.

I added the (click) to the div and also added a data-route to the <a> and can use event.target.dataset.route to get the value.

Just incase anyone else has similar issues

@Component({
  selector: 'overview-details',
  template: `
   <h2>{{ title }}</h2>
   <div (click)="handleClick($event)" [innerHTML]="regCode | sanitizeHtml"></div>
   `
})

ngOninit() {
   this.regcode = `
      <div>
          <h1>RegCode Content</h1>
          <a class="link" data-route="0">Link</a>
      </div>
  `;
}

handleClick(event: any) {
    console.log('fire', event.target.dataset.route);
    if (event.target.dataset.route == 0) {
       router.navigate([somewhere....]);
    } esle {
       router.navigate([somewhereElse....]);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.