2017-05-17 27 views
1

我試圖構建一個可以在自定義html頁面上工作的編輯器。所以我需要加載我的Angular自定義html代碼。如何在Angular中動態加載具有特定TemplateUrl的組件

我拼命尋找一種方法來加載一個不同的TemplateUrl組件每次。 我試圖看ComponentFactoryResolverngComponentOutlet,但徒勞無益。

我也試過用innerHtml來做,但是我的自定義代碼並沒有被Angular編譯,所以這意味着沒有指令不會被綁定。

有沒有人有解決方案?

我正在使用最新版本的Angular(4)。

+0

總是檢查文檔:https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html – wannadream

+0

http://stackoverflow.com/questions/40060498/angular-2-1-0 40080290 – yurzui

+0

就像我在我的帖子中說過的,我已經試過了ComponentFactoryResolver並沒有幫助,但是謝謝:) – NhlstcR

回答

0

好吧,我做到了。一切似乎都很好。

所以我使用compileModuleAndAllComponentsAsync(就像它在這裏完成:https://github.com/patrikx3/angular-compile)。

爲了讓我的組件和指令可以在編譯的元素中進行綁定,我只需將它們放在我創建的NgModuledeclarations中以編譯我的元素。

private async createFactory(opts: CompileOptions) { 
    const cacheKey = opts.template; 

    if (Object.keys(cache).indexOf(cacheKey) > -1) { 
    return cache[cacheKey]; 
    } 
    cache[cacheKey] = new Promise(async(resolve) => { 
    @Component({ 
     template: opts.template 
    }) 
    class TemplateComponent { 
     context: any 
    } 
    @NgModule({ 
     imports: opts.imports, 
     declarations: [ 
      TemplateComponent 
      // <== Insert your directives and components here 
     ] 
    }) 
    class TemplateModule { 
    } 
    const component = await this.compiler.compileModuleAndAllComponentsAsync(TemplateModule); 
    const factory = component.componentFactories.find((comp) => 
     comp.componentType === TemplateComponent 
    ); 
    if (opts.onCompiled) { 
     opts.onCompiled(component); 
    } 
    cache[cacheKey] = factory; 

    resolve(factory); 
    }) 
    return cache[cacheKey]; 
} 

謝謝大家!

0

有對角的網站一個很好的文章在此:

https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html

只是,一切都將保持相同的組件的新的聲明,只是你需要在entryComponent每個額外的條目在同一個模塊文件中添加了新的部件,其中該新組件聲明:

entryComponents: [ HeroJobAdComponent, HeroProfileComponent ],

,然後使用ComponentFactoryResolver可以dynamicall y加載該組件。請讓我知道你是否需要進一步的幫助。

+0

謝謝你的幫助,但我已經使用它,不幸的是它不能解決我的問題。我需要的是動態調用一個無限的模板,我不能全部列出它們。 – NhlstcR

+0

即使你列出了模板的無窮大,聲明是最...與聲明一起,一個條目將在同一模塊中的入口組件中進行。現在不知道任何其他動態加載組件的方法...請讓我們知道,如果你有任何其他解決方案,將很樂意知道它。 – Lambo14

相關問題