Angular2 innerHtml binding breaks data binding

让人想犯罪 __ 提交于 2020-01-22 01:03:25

问题


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

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).

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.


回答1:


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.

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



来源:https://stackoverflow.com/questions/40279899/angular2-innerhtml-binding-breaks-data-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!