我正在评估 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/