I want to open a component from a service without having to add that component to every other component which has the service.
In the service I have the following:
@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(private appRef: ApplicationRef) {}
createComponent(): void {
const comp = createComponent(MyComponent, {environmentInjector: this.appRef.injector});
this.appRef.attachView(comp.hostView);
comp.call();
}
}
The MyComponent looks something like this:
@Component({
selector: 'app-my-dialog',
standalone: true,
imports: ...,
template: '... <another-component /> ...',
})
export class MyComponent {
@ViewChild(AnotherComponent) comp!: AnotherComponent;
call(): void {
this.comp.doSomething();
}
}
Now my problem is, that the viewChild is undefined. I can't figure out, why it's not loaded correctly.
I tried to use the ViewContainerRef, but with that I can't create the component like that, because it needs an EnvironmentInjector, that only the ApplicationRef has.
I know that I could add MyComponent to the HTML of the calling Component, but I'd rather have only the service.
I use Angular 16.2.10, if that helps.
I solved the issue now, with using setTimeout.