Angular 2-使用[innerHTML]时去除点击功能 [英] Angular 2 - Stripping out click function when using [innerHTML]

查看:48
本文介绍了Angular 2-使用[innerHTML]时去除点击功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用模板上的[innerHTML]标签通过打字稿输入一些html.

I have to enter some html via typescript using the [innerHTML] tag on the template.

我正在尝试在HTML上放置点击功能:

I am trying to put a click function on the html:

status = "<img src='assets/hello.png' (click)='hello()' />";

但是单击功能会被控制台剥夺,说:

But the click function gets stripped away with the console saying:

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

我看到一些人提到使用"DomSanitizer",但是找不到解决我确切问题的示例.

I see a few people have mentioned using "DomSanitizer" but can't find an example which fixes my exact problem.

推荐答案

如果您使用的是 [innerHTML] ,Angular会剥离所有内容特定于Angular的内容.

Angular is stripping out everything Angular specific if you are using [innerHTML].

如果您需要类似的内容,则可以在运行时创建组件,如

If you need something like that, you can create components at runtime like explained in Equivalent of $compile in Angular 2
or you can use imperative code to add an event handler like

constructor(private elRef:ElementRef, private cdRef:ChangeDetectorRef) {}

someMethod() {
  this.status = "<img src='assets/hello.png' (click)='hello()' />";
  this.cdRef.detectChanges();
  this.elRef.nativeElement.querySelector('img').addEventListener('click', this.hello.bind(this);
}

这篇关于Angular 2-使用[innerHTML]时去除点击功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆