Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
ViewRef is undefined when component gets initialized on "browser back" action

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!