Ionic 4 (Angular 7) - sharing components issue

天大地大妈咪最大 提交于 2020-01-02 06:31:00

问题


I'm trying to do an extremely usual thing for such a framework like Angular. The goal is to use the same (HeaderComponent) component more than once through a shared module.

My shared.module.ts:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { IonicModule} from '@ionic/angular';

@NgModule({
    imports: [
        CommonModule, 
        IonicModule
    ],
    declarations: [
        HeaderComponent
    ],
    exports: [
        HeaderComponent
    ]
})

export class SharedModule {}

In app.module.ts I added this:

imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, SharedModule],

And in home.page.html I tried to render it this way:

<app-header></app-header>

It actually worked since browser showed me errors like

'ion-col' is not a known element

and so on for all the ionic components from the HeaderComponent.

I've found a solution for the issue over the Internet that suggest adding IonicModule.forRoot(HeaderComponent) to the imports array of the shared.module.ts, but this approach causes the following error:

'app-header' is not a known element

As if it is no longer available.


回答1:


you additionally have to add the ionic module to your shared module like this:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { HeaderComponent } from '../header/header.component';
import { IonicModule } from 'ionic-angular';

@NgModule({
  imports: [
    CommonModule,
    IonicModule
  ],
  declarations: [
    HeaderComponent
  ],
  exports: [
    HeaderComponent
  ]
})

export class SharedModule {}

if you are using ionic 4 you have to edit the import of IonicModule to this:

import { IonicModule } from '@ionic/angular';



回答2:


In my case the issue was that I was trying to include a custom component in a component that is opened with a modal. I needed to add my component to the parent page's module.



来源:https://stackoverflow.com/questions/53020439/ionic-4-angular-7-sharing-components-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!