2016-11-20 80 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>