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