【发布时间】:2020-01-05 22:53:52
【问题描述】:
我将动态组件到服务中的另一个组件,首先在服务工厂内部两个组件,我创建了可以访问 ViewContainer 的组件。但是无法创建组件!
服务:
@Injectable({
providedIn: 'root'
})
export class ModalService {
componentRef: ComponentRef<ModalTemplateComponent>;
constructor(private _modalService: BsModalService,
private resolver: ComponentFactoryResolver,
private injector: Injector) {
}
open(componentType: any) {
const contentFactory = this.resolver
.resolveComponentFactory(componentType);
const templateFactory = this.resolver
.resolveComponentFactory(ModalTemplateComponent);
const componentRef = templateFactory.create(this.injector);
componentRef.instance.container.createComponent(contentFactory);
this._modalService.show(componentRef.componentType, {class: 'modal-lg', initialState: {data: {test:true}});
}
}
组件:
selector: 'lib-modal-template',
template: `
<h1>{{title}}</h1>
<ng-container #container>
</ng-container>
`,
styleUrls: ['./modal-template.component.css']
})
export class ModalTemplateComponent implements OnInit {
title:string;
@ViewChild('container', {read: ViewContainerRef, static: true}) container: ViewContainerRef;
}
示例:
this._modalService.open(NewUserForm,...);
【问题讨论】:
标签: angular angular-dynamic-components