Angular2 innerHtml绑定中断数据绑定 [英] Angular2 innerHtml binding breaks data binding

查看:87
本文介绍了Angular2 innerHtml绑定中断数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图绑定到innerHtml,同时保持数据绑定.这不起作用(输出{{myVar}}).

I am trying to bind to innerHtml while keeping data binding. This does not work (outputs {{myVar}}).

@Component({
  selector: "test",
  template: `
    <div [innerHtml]="myHtml"></div>
  `,
})
export class TestComponent{
  title = "My Title";
  myHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer){
    this.myHtml = sanitizer.bypassSecurityTrustHtml("<h1>{{title}}</h1>");
  }
}

在我的真实应用中,myHtml是SVG文件的内容(这就是为什么我需要bypassSecurityTrustHtml)并且经常更改,因此我无法将其放在模板中(它可能来自20个不同的SVG文件)

In my real app, myHtml is the content of an SVG file (which is why I need to bypassSecurityTrustHtml) and often changes, so that I cannot put it in my template (it could come from 20 different SVG files).

如果有一种方法可以为组件动态设置templateUrl,那么它也可以解决我的问题,但是经过一段时间的搜索后,看来似乎是不可能的.

If there was a way to dynamically set the templateUrl for the component, it would also solve my problem, but after searching for quite a while it does not seem possible.

推荐答案

Angular2不处理动态添加的HTML,因此{{}}[](),...不起作用. 即使以这种方式添加的HTML与其选择器匹配,也不会创建任何组件或指令.

Angular2 doesn't process HTML added dynamically, therefore {{}}, [], (), ... isn't supposed to work. Also no components or directives are created, even when HTML added this way matches their selectors.

仅处理静态添加到组件模板的标记.

Only markup added statically to components template are processed.

在Angular 2中等效于$ comp 展示了如果您真的需要它,可以使用该方法.

Equivalent of $compile in Angular 2 demonstrates an approach if you really need it.

这篇关于Angular2 innerHtml绑定中断数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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