Enhancing Ionic2 by incorporating ModalController injection

My goal is to create a versatile datepicker component that can be integrated into any project seamlessly.

I have set up an NgModule containing various components, where I inject IonicModule to utilize all the components and directives of Ionic2.

@NgModule({
    imports: [
        CommonModule,
        IonicModule.forRoot(DatePickerModule)
    ],
    exports: [DatePickerComponent, DatePickerDirective],
    entryComponents: [DatePickerComponent],
    declarations: [DatePickerComponent, DatePickerDirective],
    providers: [DateService, nls]
})
export class DatePickerModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: DatePickerModule
        };
    }
};

One of the components makes use of Ionic modal controller to display a modal.

export class MainDirective{
  public static config:any;
    constructor(private modalCtrl:ModalController) {
    }
    openModal() {
        this.modalCtrl.create(DatePickerComponent).present();
    }
}

This NgModule is then imported into another App, where I attempt to call openModal from that app. This is how I import it:

@NgModule({
  imports: [
    IonicModule.forRoot(App),
    DatePickerModule.forRoot(),
],
})

However, when trying to do so, it results in an error '_getPortal' of undefined from the ionic-angular library. It seems like it cannot locate the app to display on.

I assume I need to pass the actual APP to forRoot for it to work properly, but I am unsure how to achieve this.

What would be the most effective approach to resolving this issue?

Answer №1

It is important to note that the forRoot method should only be called on the main module of your application. This method is responsible for setting up various providers specific to Ionic, and should not be called multiple times. Instead, simply import the IonicModule without using forRoot.

Regarding the ModalController, it is automatically provided when you import IonicModule.forRoot in the main module. There is no need to manually add it, as it relies on the Ionic App which is only accessible during the bootstrap process. Trying to include it separately would be redundant.

Answer №2

In order to make my component function as its own unique modal in Ionic, I found a solution by extending specific components.

I believe that injecting the modalcontroller into a foreign component is not efficient and should be avoided, especially if your component is not intended to be a modal itself.

It's important to extend ViewController for anything that will be displayed, as this is the baseclass that is shown every time you use a present function.

A present function essentially instructs the app to display a specified view controller.

To summarize:

Extend your component to act as a viewcontroller:

export class MyComponent extends ViewController

Include the App in your constructor:

constructor(private _app:App){}

Show your new component on the app:

this.app.present(this);

Now, your modal should be ready to be displayed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to stop the MasterComponent from rendering on every route change

I have a dropdown menu: click here to view My goal is to keep the dropdown open when the user opens a menu, but disable it if the user changes routes by clicking on another menu. How can I achieve this? Note: If the user navigates within the same route, ...

What is the purpose of assigning a value to the '#auto' ref in Angular Material?

What is the purpose of ref #auto assignment? What am I missing here? This code snippet is taken from the following Angular Material Chips example: https://material.angular.io/components/chips/examples. Here's an example usage: #auto="matAutocom ...

The system encountered difficulty handling a recursive structure

I am facing a challenge with a recursive JSON structure that needs to be stored as a series of maps with keys. The structure comprises flows and subflows that have references to each other. Here are the type declarations, noting that the issue lies in the ...

Derive the property type based on the type of another property in TypeScript

interface customFeatureType<Properties=any, State=any> { defaultState: State; properties: Properties; analyzeState: (properties: Properties, state: State) => any; } const customFeatureComponent: customFeatureType = { defaultState: { lastN ...

Mapping a TypeScript tuple into a new tuple by leveraging Array.map

I attempted to transform a TypeScript tuple into another tuple using Array.map in the following manner: const tuple1: [number, number, number] = [1, 2, 3]; const tuple2: [number, number, number] = tuple1.map(x => x * 2); console.log(tuple2); TypeScript ...

Tips on incorporating a style-tag into the body of an Angular 5 application

We offer a service that collects a vast amount of data to be displayed in an angular 5 application. The model used for displaying this data is constantly evolving and shared across multiple applications, so I need to import it dynamically. My approach inv ...

The useNavigate function cannot be utilized in a custom hook created with createBrowserRouter

Presently, I've developed a custom hook specifically for handling login and logout functionalities export function useUser() { const { token, setToken, user, setUser } = useContext(AuthContext) const navigate = useNavigate() const { ...

Angular service worker does not start automatically unless an interval is specified

After deploying my SPA to production, I'm looking for a way to automatically reload the page whenever there's an update. Setting an interval to check for updates every X minutes doesn't seem like the most efficient solution. Does anyone have ...

Experiencing difficulties establishing a connection with my NodeJs server socket and TypeScript

I've been struggling to run the code from this post and I really need some help. The code can be found at: https://medium.com/@mogold/nodejs-socket-io-express-multiple-modules-13f9f7daed4c. I liked the code as it seems suitable for large projects, but ...

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

The conversion to ObjectID did not succeed due to an issue on the front end

I have encountered an issue while trying to send a post request to create a task within a list using an API provided to me. This error occurs when I attempt to make the request in postman. Below is the schema of the post request body required by the API, ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

Deducing Generics in Typescript Functions Without Invocation of the Function

Take a look at the code snippet below; it seems like it should work without any issues. But for some reason, there is an error. Can anyone provide any insights into why this might be happening? Check out the TS-playground link const func_returnsInput = ( ...

Steps to initiate or conclude a conversation from a designated location?

I'm working on an Angular project where I have a popup dialog open. However, I want the dialog to appear from the button and close within the button itself, similar to this example: https://material.angularjs.org/latest/demo/dialog Opening and closin ...

Can we leverage Angular service styles in scss?

I am working on a change-color.service.ts file that contains the following code snippet: public defaultStyles = { firstDesignBackgroundColor: '#a31329', firstDesignFontColor: '#ffffff', secondDesignBackgroundColor: '#d1 ...

Ways to enable components to access a string dependency token

I'm currently developing an Angular application that utilizes Angular Universal for server-side rendering functionality. One interesting aspect of my project involves passing a string dependency token as a provider within the providers array in serve ...

Issue with TypeScript function overloading: Visitor Pattern not working as expected

I've been working on implementing a Visitor Design pattern, but I keep running into a compilation error that I just can't seem to resolve no matter how many hours I spend trying to find a solution... Here's my Visitor interface: export inte ...

Trouble arises when trying to choose the entries spanning all pages within Angular DataTables

I am facing an issue while trying to select checkboxes across all pages. When I change the page, the selected records are not adding to the previously selected ones. It seems to only take the records from the second page. Can anyone provide suggestions on ...

Adjusting Sass variable dynamically in Ionic 3 component using Angular 5

Is there a way to dynamically change the primary color on one page and have it apply throughout the entire app? I came across a tutorial that explains how to achieve this: . I am trying to adapt it to my own project by following these steps: In my app.ht ...