Search code examples
ionic-frameworkangular8ionic5

Add Components dynamically in DOM ionic+angular


I am following How to Dynamically Create a Component in Angular to add components dynamically inside another component. I am receiving a weired error of undefined variable.

My Component file (MessComponent)

<template #messContainer>
<p>
  mess works!
</p>
</template>

ts file

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-mess',
  templateUrl: './mess.component.html',
  styleUrls: ['./mess.component.scss'],
})
export class MessComponent implements OnInit {
  constructor() { }
  ngOnInit() {}
}

Parent Component (hosting dynamic component) module ts file

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';

import { MessComponent } from './../mess/mess.component';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule
  ],
  declarations: [HomePage, MessComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  entryComponents: [MessComponent]
})
export class HomePageModule {}

ts file

import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory, OnInit } from "@angular/core";
import { MessComponent } from "./../mess/mess.component";

@Component({
  selector: "app-home",
  templateUrl: "home.page.html",
  styleUrls: ["home.page.scss"],
})
export class HomePage implements OnInit {
  componentRef: any;
  @ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;
  createComponent() {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(MessComponent);
    this.componentRef = this.entry.createComponent(factory);
  }
  destroyComponent() {
    this.componentRef.destroy();
  }
  constructor(private resolver: ComponentFactoryResolver) {}
  ngOnInit(): void {
    this.createComponent();
  }
}

and the error I am receiving

Uncaught (in promise): TypeError: this.entry is undefined

I understand this is claiming regarding the variable entry, but don't understand why it is not identifying that variable. To conclude, why I cannot add the component?


Solution

  • Solved it. Actually I was passing wrong param to the @ViewChild(''). I was passing the template name (container) of the child while I should have passed the container name in the parent component. So created a div in the parent component with #messContainer and corrected the @ViewChild

    Important!: now #messContainer is in the parent component and everything works as expected.

    @ViewChild('messContainer', { read: ViewContainerRef, static: true }) entry: ViewContainerRef;