Javascript 加载在angular2 final中动态创建的动态组件
以前使用Javascript 加载在angular2 final中动态创建的动态组件,javascript,angular,Javascript,Angular,以前使用DynamicComponentLoader我可以这样写: import {Directive, Component, ViewContainerRef, DynamicComponentLoader} from '@angular/core'; @Directive({ selector: '[some-directive]' }) export class SomeDirective { costructor(dcl: DynamicComponentLoader, vie
DynamicComponentLoader
我可以这样写:
import {Directive, Component, ViewContainerRef, DynamicComponentLoader} from '@angular/core';
@Directive({
selector: '[some-directive]'
})
export class SomeDirective {
costructor(dcl: DynamicComponentLoader, viewContainerRef: ViewContainerRef) {
// fetch template from the server
fetch(...).then((template) => {
@Component({
selector: 'div[some-relatively-unique-attribute-name]',
template: template
})
class AdHocComponent {}
dcl.loadNextToLocation(AdHocComponent, viewContainerRef).then(() => {
console.log('success');
});
});
}
}
现在使用angular2 final和NgModules
我看到了如下示例:
(这里讨论)
动态加载HelloComponent
,但需要在创建根NgModule
时预先声明HelloComponent
如何将临时创建的组件加载到视图中
我发现:
但是,要完成这样一项简单的任务,需要大量的代码。这可能就是您想要的:
export class App {
@ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef;
constructor(private compiler: Compiler) {}
addItem () {
@NgModule({declarations: [HelloComponent]})
class DynamicModule {}
this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
.then(({moduleFactory, componentFactories}) => {
const compFactory = componentFactories
.find(x => x.componentType === HelloComponent);
const cmpRef = this.viewContainerRef.createComponent(compFactory, 0);
});
}
}
另请参见live
相关问题: