Since I haven't found any answer or similar case I'm posting this question here.
My App has the following structure:
- AppModule
- LayoutModule
- MainComponent
- SidebarComponent
- SidebarService {providedIn: 'root'}
- ContentModule
- ContentComponent
- ContentService {providedIn: 'ContentModule'}
- ContentSidebarComponent
- AnotherModule
- AnotherComponent
- AnotherService {providedIn: 'AnotherModule'}
- AnotherSidebarComponent
- LayoutModule
There are a lot more modules in the style of ContentModule and AnotherModule.
Inside the SidebarComponent is a view container used for dynamic component generation.
The SidebarService contains a method like generateSidebar(component: any): void
which is called inside ContentComponent: generateSidebar(ContentSidebarComponent)
and AnotherComponent: generateSidebar(AnotherSidebarComponent)
and handles the dynamic component loading like this:
Dynamic Component Loader with custom injector
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(...);
const viewContainerRef = viewContainer.viewContainerRef;
viewContainerRef.clear();
let componentRef: ComponentRef<any>;
let injector: Injector|undefined = undefined;
injector = Injector.create({
providers: [
{
provide: ContentService, //AnotherService respectively
useClass: ContentService, //AnotherService respectively
deps: []
}
]
})
componentRef = viewContainerRef.createComponent(
componentFactory,
0,
injector
);
There is no error like "No provider for ...".
When accessing the ContentComponent, ContentSidebarComponent is generated inside SidebarComponent properly.
When accessing the AnotherComponent, AnotherSidebarComponent is generated inside SidebarComponeent properly.
The Problem ContentService is also used inside ContentComponent, and there are some properties of ContentService that get changed. It seems like ChangeDetection is not working in the ContentSidebarComponent because the properties of ContentService aren't changing there.
By the way: Both services throw errors if there are multiple instances. So this is not the case and not the problem.
How can I trigger ChangeDetection inside the dynamically generated component when a value of a property of an injected service changes?
Thanks in advance.
useExisting
instead ofuseClass
is the solution ... but that gives me circular dep on ContentService