【问题标题】:Angular 2 (Typescript) - Remote development of components and dynamic injectionAngular 2 (Typescript) - 组件的远程开发和动态注入
【发布时间】:2017-01-30 17:27:59
【问题描述】:

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

【问题讨论】:

    标签: javascript angular typescript babeljs


    【解决方案1】:

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

    我在查看 Plunkr 主页时偶然发现了这个示例。

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

    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 {}
    

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多