动态组件
上一篇写的是动态创建组件,但是这个组件必须在app.module的entryComponents中声明
现在这个动态组件是包含在module中不用加入entryComponents
app.module.ts
import {
Component,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
Compiler,
Injector,
NgModule,
ComponentFactory,
ReflectiveInjector
} from '@angular/core';
import { DynamicComponent } from './dynamic/dynamic.component';
import { COMPILER_PROVIDERS } from '@angular/compiler';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
username = 'zengwe';
compiler: Compiler;
@ViewChild('content', { read: ViewContainerRef }) content: ViewContainerRef;
@ViewChild('contentBymodule', { read: ViewContainerRef }) contentBymodule: ViewContainerRef;
constructor(private componentFactory: ComponentFactoryResolver, private injector: Injector) {
this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);
this.compiler = this.injector.get(Compiler);
}
add() {
const component = this.componentFactory.resolveComponentFactory(DynamicComponent);
component.inputs.push({propName: 'dd', templateName: 'ss'});
const com = this.content.createComponent(component);
console.log(com.instance);
com.instance.dd = 'dd传的值';
com.instance.out.subscribe((res) => {
console.log(res);
});
}
remove() {
this.content.clear();
}
createDynamicComponentByModule(tpl, func = ''): ComponentFactory<any> {
@Component({
selector: 'app-dynamic-component',
template: tpl
})
class Dynamic2Component {
constructor() {
console.log('DynamicComponent');
// this.init();
}
// init = new Function('functi');
}
@NgModule({
declarations: [Dynamic2Component],
imports: []
})
class DModule {
}
return this.compiler.compileModuleAndAllComponentsSync(DModule)
.componentFactories.find(comfac => comfac.componentType === Dynamic2Component);
// .then(factory => factory.componentFactories.find(x => x.componentType === Dynamic2Component));
}
createOthenDynamicComponent(tpl: string) {
const componentInstance = this.contentBymodule.createComponent(this.createDynamicComponentByModule(tpl));
console.log(componentInstance.instance);
}
}
在constructor中用了
this.injector = ReflectiveInjector.resolveAndCreate(COMPILER_PROVIDERS, injector);
主要还是在编译的时候会出现complier找不到的这种情况
tpl这个参数主要动态添加模板文件,当然可以在Dynamic2Component中运用js中的方法动态生成方法