angular - Angular 8:使用服务创建动态组件。错误:无法读取未定义的属性“createComponent”
问题描述
我正在尝试使用服务来创建动态组件。当代码在组件中时,我在创建动态组件时没有问题。当我将代码移动到服务时,我收到有关未找到 createComponent 的错误。
我在“ngAfterViewInit”中有我的函数调用,这是大多数人在寻找解决方案时遇到的问题。我一直试图弄清楚为什么当我将代码放入服务时它不起作用。我也尝试过制作导演,但效果不佳。
这是堆栈闪电战中的代码 https://stackblitz.com/edit/angular-ikshag
组件和服务代码如下。
应用程序组件
import { GenService } from './gen.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
name = 'Angular';
constructor(private gen: GenService) { }
ngAfterViewInit() {
this.gen.createComp("yo");
}
}
服务
import { Injectable, ComponentFactoryResolver, ViewChild,ViewContainerRef } from '@angular/core';
import { ChildComponent } from './child/child.component';
@Injectable({
providedIn: 'root'
})
export class GenService {
@ViewChild('container', { static: true }) newsHost: ViewContainerRef; //this allow the targeting needed to add component
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
createComp(message) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
let componentRef = this.newsHost.createComponent(componentFactory);//adds it to the screen
}//end of bot reply
}
子组件只是表示它有效的默认值。
解决方案
这不是那么简单。您正在阅读的主题(angular-dynamic-components)很长。
看一下src/app/dialog/insertion.directive.ts
,然后在 ng-template 中使用其选择器引用它(而您使用的container
选择器不映射到任何角度指令)。
该指令已viewContainerRef
注入,用于访问方法createComponent
。ViewChild 也相当复杂:@ViewChild(InsertionDirective) insertionPoint: InsertionDirective
.
所以你必须做的步骤是:
- 按照博客中的说明制定指令
<ng-template>
在标签中使用它的选择器@ViewChild
使用指令类更新您的- 访问
viewContainerRef
您的指令(必须是公开的)以使用createComponent
方法