2017-05-17 29 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

相关问题