I am trying to use a service to create dynamic components. I didn't have issues creating dynamic component when the code was in a component. When I move my code to a service I get an error about createComponent not found.
I have my function call in 'ngAfterViewInit', this was most people issues were when I looking for solutions. I been trying to figure out why my code doesn't work when I put it in a service. I have also tried making a director and that didn't work as well.
Here is the code in a stack blitz https://stackblitz.com/edit/angular-ikshag
The component and the service code is below.
app.component
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");
}
}
service
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
}
child component is just the default that says it works.
@ViewChild
inside a service, it should be a component thing... Where did you find this ?this.gen.createComp("yo", this.newsHost)
)