1

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?

Apollo
  • 1,296
  • 2
  • 11
  • 24
  • 1
    Yep, @ViewChild are available in AfterViewInit. See https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined – Arnaud Denoyelle Apr 20 '22 at 13:34
  • 2
    @ArnaudDenoyelle when the decorator includes `static: true`, then it becomes available in ngOnInit. –  Apr 20 '22 at 13:40
  • 1
    @Apollo do you have some `routeReuseStrategy` in your routing logic ? –  Apr 20 '22 at 13:41
  • @ArnaudDenoyelle hmm then I run into issues with changed after init. Perhaps I need to use Change Detection on push here. And I don't use `routeReuseStrategy`. – Apollo Apr 21 '22 at 05:36
  • @temp_user I changed it to `static: true` but it is still undefined in my loadComponents method. Any ideas why? Now even the initial load does not work. – Apollo Apr 21 '22 at 05:37

1 Answers1

0

I've got a solution. I created a new sub component which wraps the placeholder. I did not need ChangeDetection OnPush in the view ref. But the loadComponents not gets triggered in ngOnChanges.

Apollo
  • 1,296
  • 2
  • 11
  • 24