Home > database >  Angular 14 issue in method loading component at runtime
Angular 14 issue in method loading component at runtime

Time:06-25

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?

CodePudding user response:

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>
  • Related