【问题标题】:Add Components dynamically in DOM ionic+angular在 DOM ionic+angular 中动态添加组件
【发布时间】:2020-08-21 10:29:19
【问题描述】:

我正在关注How to Dynamically Create a Component in 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() {}
}

父组件(托管动态组件) 模块 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 的声明,但不明白为什么它没有识别该变量。总结一下,为什么我不能添加组件?

【问题讨论】:

    标签: ionic-framework angular8 ionic5


    【解决方案1】:

    解决了。实际上我将错误的参数传递给@ViewChild('')。我正在传递子组件的模板名称(容器),而我应该在父组件中传递容器名称。所以在父组件中用#messContainer创建了一个div,并更正了@ViewChild

    重要! 现在#messContainerparent component 中,一切正常。

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

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 2016-09-26
      • 2021-04-27
      • 2017-07-17
      • 2019-02-22
      • 2017-12-09
      • 2018-11-14
      • 2022-07-12
      • 1970-01-01
      相关资源
      最近更新 更多