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

标签 javascript angular typescript babeljs

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

最佳答案

是的 - 请看这里: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 {}

关于javascript - Angular 2 (Typescript) - 组件的远程开发和动态注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41941877/

相关文章:

javascript - 单击时使用选项卡在页面底部显示隐藏的内容

html - 关键帧动画无法正常工作 - CSS

Angular 2 - 一个组件触发页面上另一个组件的刷新

typescript - 使用 pulumi Typescript 获取 Elasticache 端点

javascript - 将鼠标悬停在单元格上时,在表格单元格 (td) 的工具提示上获取表格标题 (th)

javascript - IGraph 中的 VisNetwork - 无法实现顶点的簇颜色

javascript - 滚动到元素底部时触发事件?

angular - 在父组件的子组件中使用 ng-template

Angular TS Lint onInit 与 ngOnInit

reactjs - 使用 SVG 作为 React 组件,并将图像链接作为 prop?