Search code examples
angularionic4

Ionic 4 (Angular 7) - sharing components issue


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.


Solution

  • 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';