-1

I am using Angular 14 and I'm trying to load a component at runtime like this:

import { Component, ViewChild, ViewContainerRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      
      @ViewChild('dropdownComponent', { read: ViewContainerRef })
      
      dropdownComponent!: ViewContainerRef;
    
      constructor(private ref: ViewContainerRef) {}
    
      async loadit() { 
        const { DropdownComponent } = await import('./components/dropdown/dropdown.component');
        this.dropdownComponent.clear();
        this.dropdownComponent.createComponent(DropdownComponent); 
      }
    }

I'm getting this error:

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'clear')
TypeError: Cannot read properties of undefined (reading 'clear')

How can I fix this?

  • At which point of time do you call `loadit()`? How does the template look like? – JSON Derulo Jun 24 '22 at 12:40
  • It's dangerous to use non-null-assertion `!` with `@ViewChild` because in reality it can totally happen that the view child is not available, due to timing and conditional rendering. – JSON Derulo Jun 24 '22 at 12:42
  • @JSONDerulo The component that I'm trying to load is an empty generated component..just a bit of text in it. This component is a standalone component (feature of NG14) and I want to lazy load it without routing ... You know another way to do this? – ianventor2300 Jun 24 '22 at 12:47
  • Could you show the relevant part of `app.component.html`? – JSON Derulo Jun 24 '22 at 12:49
  • It's just this: – ianventor2300 Jun 24 '22 at 13:03

1 Answers1

0

Have a look into the documentation of ViewChild. You are using a string to select your view child, in this case you need a corresponding template reference variable. To create it, add something like the following to your app.component.html:

<div #dropdownComponent></div>
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56