我正在尝试使用服务来创建动态组件。当代码在组件中时,我在创建动态组件时没有问题。当我将代码移动到服务时,我收到有关未找到 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
}
子组件只是表示它有效的默认值。