首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular 2 (Typescript) -远程开发组件和动态注入

Angular 2 (Typescript) -远程开发组件和动态注入
EN

Stack Overflow用户
提问于 2017-01-31 01:28:00
回答 1查看 179关注 0票数 3

我正在评估Angular 2作为可组合管理控制台的核心技术,它的主要要求是可扩展和可定制。外部开发人员应该可以开发自己的组件,并以某种方式将其注入到我的“只读”框架中。只读意味着开发人员将无法访问(或编辑)框架的源代码。相反,他们可以简单地专注于组件资源(.html、.ts/.js文件)的开发,而不需要知道“主”应用程序的结构,并通过servlet(或其他)静态地为它们提供服务。这至少在理论上是可行的吗?我可以有一个动态导入(从预定义的位置)声明和理解基于typescript的组件的“主”应用程序模块吗?

EN

回答 1

Stack Overflow用户

发布于 2017-08-27 12:41:36

是的-请看这里:https://plnkr.co/edit/fdP9Oc?p=info

我在浏览Plunkr主页时偶然发现了这个例子。

您可以将组件作为对象参数传递给编译它们的函数。

代码语言:javascript
复制
import {Compiler, Component, NgModule, OnInit, ViewChild,
  ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `<h1>Dynamic template:</h1>
             <div #container></div>`
})
export class App implements OnInit {
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;

  constructor(private compiler: Compiler) {}

  ngOnInit() {
    this.addComponent(
      `<h4 (click)="increaseCounter()">
         Click to increase: {{counter}}
       </h4>`,
      {
        counter: 1,
        increaseCounter: function () {
          this.counter++;
        }
      }
    );
  }

  private addComponent(template: string, properties?: any = {}) {
    @Component({template})
    class TemplateComponent {}

    @NgModule({declarations: [TemplateComponent]})
    class TemplateModule {}

    const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
    const factory = mod.componentFactories.find((comp) =>
      comp.componentType === TemplateComponent
    );
    const component = this.container.createComponent(factory);
    Object.assign(component.instance, properties);
    // If properties are changed at a later stage, the change detection
    // may need to be triggered manually:
    // component.changeDetectorRef.detectChanges();
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41941877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档