Добавляйте компоненты динамически в DOM ionic + angular - PullRequest
0 голосов
/ 06 мая 2020

Я следую Как динамически создавать компонент в Angular, чтобы динамически добавлять компоненты внутри другого компонента. Я получаю устаревшую ошибку неопределенной переменной.

Файл моего компонента (MessComponent)

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

ts файл

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() {}
}

Родительский компонент (динамический хостинг c компонент) модуль ts файл

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 файл

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();
  }
}

и ошибка, которую я получаю

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

Я понимаю, что это утверждение относительно переменной entry, но не понимаю, почему он не идентифицирует эту переменную. В заключение, почему я не могу добавить компонент?

1 Ответ

0 голосов
/ 07 мая 2020

Решил. На самом деле я передавал неправильный параметр @ViewChild(''). Я передавал имя шаблона (контейнера) дочернего элемента, в то время как я должен был передать имя контейнера в родительский компонент. Итак, создал div в родительском компоненте с помощью #messContainer и исправил @ViewChild

Важно!: теперь #messContainer находится в parent component, и все работает, как ожидалось.

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