“ ion-title”不是一个已知元素:在动态创建组件时

时间:2018-11-23 06:07:37

标签: angular ionic-framework components

我正在尝试动态添加组件ngOnInit。创建组件时,出现此错误。

 "Uncaught (in promise): Error: Template parse errors: 'ion-title' is not a 
 known element"

这是我的代码:

TS:

import { Component,Input, OnInit, Compiler, Injector, VERSION, ViewChild, 
         NgModule, NgModuleRef, ViewContainerRef, AfterViewInit,
         ComponentFactoryResolver } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ViewController } from 'ionic-angular';

@Component({
     selector: 'page-cashbalancemodal_rpt',
     template: '<ng-container #dynamicTemplate></ng-container>',
})

export class Cashbalancemodal_rptPage {

   @ViewChild('dynamicTemplate', {read: ViewContainerRef}) 
              viewContainerRef;

   constructor(){.......}

   ngOnInit() {
         let template = this.navParams.get("modaltemplate");
         let myTemplateUrl = "assets/templates/"+template+".html";

         const tmpCmp = Component({
             templateUrl: myTemplateUrl
         })(class {});

         const tmpModule = NgModule({
             declarations: [tmpCmp],
             entryComponents: [tmpCmp],
        })(class {});


        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
          .then((factories) => {
          const f = factories.componentFactories[0];
          const cmpRef = this.viewContainerRef.createComponent(f);
          cmpRef.instance.name = 'dynamic';
      })
  }

}

我遇到了很多解决方案。最常用的解决方案之一是在app.module.ts中添加“ IonicModule”。我也是那样但是无法摆脱这个错误。

app.module.ts

 import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
 @NgModule({
       imports: [
           BrowserModule,
           IonicStorageModule.forRoot(),
           HttpModule,
           IonicModule.forRoot(MyApp),
           ComponentsModule,
      ],
 })

请帮助解决此错误。

1 个答案:

答案 0 :(得分:2)

由于您正在tmpCmp中设置的tmpModule中使用离子成分,

您需要在该模块中导入IonicModule

     const tmpModule = NgModule({
         declarations: [tmpCmp],
         imports:[IonicModule],
         entryComponents: [tmpCmp],
    })(class {});