Angular 2将动态模板解析为字符串 [英] Angular 2 parse dynamic template as string
问题描述
我正在使用angular 2.1,并且想要动态导入模板,这是来自后端的字符串.
I'm using angular 2.1 and want to dynamically import a template witch is a string from the backend.
我已经使用ComponentFactoryResolver
动态加载我的父容器,现在我需要创建他的内容女巫,如下所示:
I already use ComponentFactoryResolver
to load dynamically my parent container, now I need to create his content witch can look like this:
<my-component>
<my-nested-component>
<my-nested-component>
<my-component>
组件已经在我的应用程序中,我只需要从模板字符串创建它们并将它们加载到父级中即可.
Components are already in my applications, I just need to create them from the template string and load them into the parent.
如果无法从字符串模板创建组件,是否可以通过延迟加载组件来完成?我看到了路由器的延迟加载,但是在这里我处于一条路由之下,只想在某些组件上延迟加载
If create components from string template is not possible, is it possible to do it with lazy loading components ? I see lazy loading with the router but here I under a route and want lazy loading on some composent only
有可能吗?我知道通过执行 https://stackoverflow.com/a/39044539/541867
Is it possible ? I know it was possible with angular 2 beta or RC by doing this https://stackoverflow.com/a/39044539/541867
PS:如果您想知道为什么我需要有一个模板作为字符串来自后端,那是因为某些组件的UI来自外部插件,所以他们只使用应用程序可用的一组组件,但是可以他们想要的布局,所以我不能在@Component
模板下使用它.
PS: if you want to know why I need to have a template as string coming from the backend it's because the UI of some component is coming from external plugin, they just use a set of component available is the application but can do the layout they want so I can't have it under a @Component
template.
这是我尝试加载的第一个字符串模板的要旨: https://gist .github.com/jaumard/918dfc573b01263467e89adc8ad86f77
here is a gist of a first string template I try to load: https://gist.github.com/jaumard/918dfc573b01263467e89adc8ad86f77
推荐答案
如果将模板插入innerHtml属性并使用DomSanitizer,它将像组件一样转换它,从而为您带来延迟加载效果.
If you inject your template in the innerHtml attribute and use the DomSanitizer, it will translate it just like a component, giving you the lazy load effect.
<div [innerHTML]="myComponentsTemplate"></div>
这篇关于Angular 2将动态模板解析为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!