d100
d100

Reputation: 13

Ionic 4 - Using the same popover component on every page

I have a ion-toolbar I want to remain consistent throughout every page of the app, specifically I want the button on the right hand side to load a popover with page-agnostic functions (logout, etc).

home.page.html:

 <ion-header translucent>
  <ion-toolbar color="primary">
    <ion-buttons slot="primary">
      <ion-button slot="end">
        <button mat-button (click)="presentPopover($event)"><mat-icon>more_vert</mat-icon></button>
      </ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-header>

The presentPopover code is as follows:

async presentPopover(ev: any) {
    const popover = await this.popoverController.create({
      component: MainPopoverComponent,
      event: ev,
      translucent: true
    });
    return await popover.present();
  }

As I understand it, the best way to have the same component appear on multiple pages is to export the component as part of a larger module (component.module.ts):

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { MainPopoverComponent } from './main-popover/main-popover.component';

@NgModule({
 imports:      [ CommonModule, IonicModule ],
 declarations: [ MainPopoverComponent,],
 exports:      [ MainPopoverComponent,
                 CommonModule, FormsModule ]
})
export class ComponentsModule { } 

The import process is no problem and the page loads fine, but when I click the button I get an error:

Error: No component factory found for ComponentsModule. Did you add it to @NgModule.entryComponents?

Adding it to the entryComponents throws the error:

ComponentsModule cannot be used as an entry component.

I'm at a loss as to how to proceed.

Upvotes: 1

Views: 1593

Answers (1)

Praveen Patel
Praveen Patel

Reputation: 347

you can add MainPopoverComponent in app.module.ts

@NgModule({
  declarations: [MainPopoverComponent ],
  entryComponents: [MainPopoverComponent ],
  ...
  bootstrap: [AppComponent]
})

and then you can use it like this in any pages/components

import { MainPopoverComponent } from './path-of-component';

async presentPopover(ev: any) {
    const popover = await this.popoverController.create({
      component: MainPopoverComponent,
      event: ev,
      translucent: true
    });
    return await popover.present();
}

Upvotes: 3

Related Questions