简体   繁体   中英

bind to click event to external content when using innerHTML angular

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....]);
}

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));
}

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....]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM