2016-11-20 79 views
0

我使用的是角2.1,并且想要动态地导入模板巫婆是来自后端的字符串。Angular 2将动态模板解析为字符串

我已经使用ComponentFactoryResolver动态加载我的父容器,现在我需要创建自己的内容巫婆可以是这样的:

<my-component> 
    <my-nested-component> 
    <my-nested-component> 
<my-component> 

组件已经在我的应用程序,我只需要在创建它们模板字符串并将它们加载到父级。

如果从字符串模板创建组件是不可能的,是否有可能通过延迟加载组件来实现?我看到延迟加载与路由器,但在这里我在一个路线下,并希望一些compox的延迟加载只

这可能吗?我知道这是可能的角2测试版或RC通过这样https://stackoverflow.com/a/39044539/541867

PS:如果你想知道为什么我需要有一个模板字符串由这是因为一些组件的UI是从外部来的后端未来插件,他们只是使用一组可用的组件是应用程序,但可以做他们想要的布局,所以我不能在@Component模板下。

编辑:这是第一串模板的要点我尝试加载:https://gist.github.com/jaumard/918dfc573b01263467e89adc8ad86f77

+0

我不知道如果我这样做是正确的,但你可以存储一个字符串变量和使用' * ngIf'当他们没有数以百万计的时候......我的意思是'<我的嵌套组件* ngIf =“string =='嵌套'”>'或者如果你有很多这些组件可以将它们存储在数组中并使用'* ngFor'。我知道这可能不够专业,但当我在做类似的工作时,它很有用。 –

+0

我添加了一个我的第一个模板字符串的样子(但将来会有更多更多不同的东西),我认为它不会像你说的那样工作。我错了吗 ? – jaumard

回答

1

如果你注入你的模板中的innerHTML属性,并使用DomSanitizer,将它翻译就像一个组件,给你延迟加载效果。

<div [innerHTML]="myComponentsTemplate"></div>

0

车削串成组件被加载的分量被阻止出于安全原因后。 [https://angular.io/guide/security]

构建动态模板服务似乎是最佳实践。发送来自服务器的值将被设置为基类,我认为可以提供你正在尝试做的事情。

存在脱机模板编译器(https://angular.io/guide/security#offline-template-compiler) 显示动态组件创建的示例在https://angular.io/guide/dynamic-form#dynamic-template中举例说明。

我认为这只需要一点点重构具有动态组件的方法,它被称为最佳实践。

要回答,如何将字符串转换为需要用bypassSecurityTrustHtml()绕过安全性的组件。我更喜欢使用管道。 https://angular.io/guide/security#bypass-security-apis

我发现这是在一个论坛上https://forum.ionicframework.com/t/inserting-html-via-angular-2-use-of-domsanitizationservice-bypasssecuritytrusthtml/62562/2

import {Pipe, PipeTransform} from '@angular/core'; 
import {DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser'; 

@Pipe({ 
    name: 'safe' 
}) 
export class SafePipe implements PipeTransform { 

constructor(protected _sanitizer: DomSanitizer) { 

} 

    public transform(value: string, type: string = 'html'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl { 
    switch (type) { 
     case 'html': return  this._sanitizer.bypassSecurityTrustHtml(value); 
     case 'style': return this._sanitizer.bypassSecurityTrustStyle(value); 
     case 'script': return this._sanitizer.bypassSecurityTrustScript(value); 
     case 'url': return this._sanitizer.bypassSecurityTrustUrl(value); 
     case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value); 
     default: throw new Error(`Invalid safe type specified:  ${type}`); 
    } 
} 

} 

要实现只使用<component-container [innerHtml]='this.safteyPipe.transform(TemplateComponentString)'></component-container>