I have a component which contains <ng-template #placeholder></ng-template>
in its template to insert components dynamically. In OnInit a "loadComponents" method is called which uses the viewRef, but is unable on the second time it loads:
@ViewChild("placeholder", { read: ViewContainerRef, static: false })
private viewRef: ViewContainerRef;
private loadComponents() {
if (this.viewRef) {
this.viewRef.clear();
this.criteria.forEach((criterion) => {
if (Object.keys(this.componentMap).includes(criterion.type)) {
const componentFactory = this.cfr.resolveComponentFactory(
this.componentMap[criterion.type]
);
const componentRef = this.viewRef.createComponent(componentFactory);
}
});
}
}
This component is a form for a search component which it includes.
After starting the search, the search component shows the data below and has links to the detail views. But when I open the detail view and go back to the search page -- which holds the search criteria in a store -- the viewRef is undefined. When I check it "later" with the Angular Tools then viewRef is defined. So I guess it is injected after OnInit.
Any ideas how to fix this?