简体   繁体   English

使用innerHTML angular时将click事件绑定到外部内容

[英]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 内容通过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. 我正在尝试监听<a>标记的onClick事件。 The <a> is a route redirect. <a>是路由重定向。 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. 我试过设置handleClick函数,但是我认为这不是正确的方法。

I also thought maybe using a ElementRef - in this case #view but would jquery light be better in this case. 我还认为也许使用ElementRef在这种情况下#view但在这种情况下jquery light会更好。

@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. Angular不处理通过[innerHTML]="..."添加的HTML或任何其他方式。 Bindings like (click)="..." work only when added statically to a comopnents template. (click)="..."这样的绑定在静态添加到组件模板时才起作用。

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. 我在div添加了(click) ,还向<a>添加了data-route ,并且可以使用event.target.dataset.route获取值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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