A simple guide on how to send an Angular component to the Nebular dialog service

My current project involves creating a web dialog in Angular6 using Nebular components. Initially, I used the method of passing an <ng-template> reference in the following manner:

openAddDialog = (dialogTemplate: TemplateRef<any>) => {
    this.dialogServiceRef = this.dialogService.open(dialogTemplate);
}

This approach worked without any issues. However, I now need to pass a component as a parameter like so:

dialogService.open(MyComponent);

My project structure is organized as follows:

|_ pages
|   |_ pages.module.ts
|   |_ patient
|      |_ patient.module.ts
|      |_ patient.component.ts
|      |_ patient.component.html
|
|_ shared
    |_ shared.module.ts
    |_ components
    |   |_ search-bar.component.ts
    |   |_ search-bar.component.html
    |
    |_ modal-form
        |_ modal-form.component.ts
        |_ modal-from.component.html

I have added the ModalFormComponent to the declarations, exports, and entryComponents in the shared module. Additionally, I imported it in the SearchBar component and attempted to run the function upon clicking a button in the searchBar:

openAddDialog = () => {
    this.dialogServiceRef = this.dialogService.open(ModalFormComponent);
}

Upon testing, I encountered the following error in the browser console:

ERROR Error: No component factory found for ModalFormComponent. Did you add it to @NgModule.entryComponents?
    at noComponentFactoryError (core.js:19453)
    at CodegenComponentFactoryResolver.resolveComponentFactory (core.js:19504)
    at NbPortalOutletDirective.attachComponentPortal (portal.js:506)
    at NbDialogContainerComponent.attachComponentPortal (index.js:17128)
    at NbDialogService.createContent (index.js:17336)
    at NbDialogService.open (index.js:17295)
    at SearchBarComponent.openAddDialog (search-bar.component.ts:46)
    at Object.eval [as handleEvent] (SearchBarComponent.html:11)
    at handleEvent (core.js:34777)
    at callWithDebugContext (core.js:36395)

Do you have any insights on what might be causing this issue and how I can resolve it?

Answer №1

Ensure to utilize the context parameter to transfer all the necessary parameters.

As an illustration, let's consider the scenario where we have the following SimpleInputDialogComponent:

import { Component, Input } from '@angular/core';
import { NbDialogRef } from '@nebular/theme';

@Component({
  selector: 'ngx-simple-input-dialog',
  templateUrl: 'simple-input-dialog.component.html',
  styleUrls: ['simple-input-dialog.component.scss'],
})
export class SimpleInputDialogComponent {

  title: String;
  myObject: MyObject;

  constructor(protected ref: NbDialogRef<SimpleInputDialogComponent>) {
  }

  cancel() {
    this.ref.close();
  }

  submit(value: String) {
    this.ref.close(value);
  }
}

Remember, when passing title and myObject, make use of the context parameter:

const sampleObject = new MyObject();
this.dialogService.open(SimpleInputDialogComponent, {
      context: {
        title: 'Enter template name',
        myObject: sampleObject,
      },
    })

Answer №2

Ensure to place the component in the entryComponents section of the module, whether it's the main module or a child module, based on your specific scenario.

import {NgModule} from '@angular/core';

import {
  //...
  NbDialogModule
  //...
} from '@nebular/theme';


@NgModule({
 declarations: [
 //...,
 ModalFormComponent,
 //...
 ],
 entryComponents: [
  //...
  ModalFormComponent,
  //...
 ],
 imports: [
 //...
 // NbDialogModule.forChild() or NbDialogModule.forRoot()
 //...
],
 providers: [
  //...
 ],
})
 export class ExampleModule{
}

Following this step should resolve the issue you are facing.

Answer №3

According to the recommendations in nebular documents, the following code snippet is advised:

showDialog() {
 this.dialogService.open(yourComponent, {
   context: {
     title: 'Passing a title to the dialog component',
   },
 });
}

Answer №4

resolution : acquire the parameters using ngOnInit instead of the constructor

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

What is the process for including a unique attribute for child elements within a React component using TypeScript?

I have a component that creates a Table of Contents (TOC) and List for the child elements. These children can be any JSX.Element. Here is an example... <SectionScrollList> <View key="first"/> <View key="second"/> ...

Interpolating strings in a graphQL query

Exploring the world of Gatsby and its graphQL query system for asset retrieval is a fascinating journey. I have successfully implemented a component called Image that fetches and displays images. However, I am facing a challenge in customizing the name of ...

Tips on transferring information to the graphical user interface

Here is my code snippet: signup.post('/signup', urlendcodedParser, async(req: Request, res: Response) => { const username = req.body.username; const password = req.body.password; const age = req.body.age; const email = req ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...

No slides will be displayed in Ionic 2 once the workout is completed

Here is the result of the JSONOBJ:https://i.sstatic.net/8vyQd.png In my home.html file, I have ion-card containing a method called navigate(), which is structured as follows: navigate(event, exercise, exercise2, exercise3, exercise4){ this. ...

Issue with BehaviorSubject<Object[]> causing incorrect array data upon initial subscription

I am facing an issue with a BehaviorSubject where the first .subscribe callback is returning an Array with 6 Objects. Strangely, in console output, it shows length: 6, but every for-loop I iterate through the array only runs 5 times and even when I log arr ...

The constant value being brought in from an internal npm package cannot be determined

I have developed an internal npm package containing shared types and constants. My project is built using TypeScript with "target": "ESNext" and "module": "NodeNext". Within one of my files, I define: export type Su ...

Issues with tracking changes in Vue.js when using reactive variables

After triggering a click event, I am attempting to choose a message from a json file. However, I am encountering an issue where the first click does not seem to select anything. Upon the second click, the selected messages are duplicated, and this pattern ...

What is the procedure for linking the value (<p>John</p>) to the mat form field input so that it displays as "John"?

Can I apply innerHTML to the value received from the backend and connect it to the matInput? Is this a viable option? ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

Is there an issue with this return statement?

retrieve token state$.select(state => { retrieve user access_token !== ''}); This error message is what I encountered, [tslint] No Semicolon Present (semicolon) ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...

The component 'ProtectRoute' cannot be utilized within JSX

While using typescript with nextjs, I encountered an issue as illustrated in the image. When I try to use a component as a JSX element, typescript displays the message: ProtectRoute' cannot be used as a JSX component. import { PropsWithChildren } from ...

Why is it that Chart.js fails to render in a child component, yet works perfectly in the parent component?

I attempted to create a chart in a parent component using a child component but encountered some difficulties. Here is my code: Parent component: @Component({ selector: 'app-tickets', template: '<canvas id="newChart">< ...

Error message encountered following the removal of an undesirable type from an array in Typescript

When working with TypeScript, I am facing an issue. I have an array defined as Array<string|undefined, and my goal is to filter out the undefined values from this array and assign the resulting array to a variable of type Array<string>. However, I ...

When compiling TypeScript, the exported module cannot be located

I've encountered an issue while working on my TypeScript project. Upon compiling my code with the following configuration: { "compilerOptions": { "target": "ESNext", "module": "ESNext", & ...

Save Component Characteristics in a type-safe array

Is it possible in Svelte to define a strongly typed array that matches the properties exported by a specific component? For instance, if I have the following code snippet, const things = [], is there a way for Svelte to recognize that each item within the ...

Struggling to fetch information with Angular HttpClient from an API that sends back a JSON response with an array

As a beginner in Ionic and Angular, I am attempting to call an API and then showcase the team names within the template of my project. Despite following numerous tutorials and videos, I seem to be stuck as the JSON response returns an object with results f ...

Creating a type-safe dictionary for custom theme styles in Base Web

In my Next.js project, I decided to use the Base Web UI component framework. To customize the colors, I extended the Theme object following the guidelines provided at . Interestingly, the documentation refers to the theme type as ThemeT, but in practice, i ...

What is the process for converting this lambda type from Flow to TypeScript?

Currently, I am in the process of converting the below code snippet from Flow to TypeScript let headAndLines = headerAndRemainingLines(lines, spaceCountToTab), header: string[] = headAndLines.header, groups: string[][]= headAndLines.groups, ...