Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Components as content" demo in ng-bootstrap and the "Component Interaction" section in the Angular documentation, I haven't been able to achieve this functionality or find a suitable example.

While I can successfully open the modal, integrating dynamic content has proven to be a challenge. I've experimented with both the @Input approach and using variables, but unfortunately, neither method has yielded successful results. Additionally, I have included ModalService in the providers within app.module.ts. Here is what I have attempted with both strategies:

page.component.html:

<a (click)="modal('message')">
<template ngbModalContainer><my-modal [data]="data"></my-modal></template>

page.component.ts:

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalService } from '../helpers/modal.service';
import { ModalComponent } from '../helpers/modal.component';

@Component({
  selector: 'app-page',
  templateUrl: './page.component.html',
  styleUrls: ['./page.component.scss'],
  entryComponents: [ ModalComponent ]
})

export class PageComponent {
  data = 'customData';
  constructor (
    private ngbModalService: NgbModal,
    private modalService: ModalService
   ) { }

  closeResult: string;
  modal(content) {
    this.data = 'changedData';
    this.modalService.newModal(content);
    this.ngbModalService.open(ModalComponent).result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${reason}`;
    });
  }
}

modal.service.ts:

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';

@Injectable()
export class ModalService {
  private modalSource = new Subject<string>();
  modal$ = this.modalSource.asObservable();
  newModal(content: string) {
    this.modalSource.next(content);
  }
}

modal.component.ts:

import { Component, Input, OnDestroy } from '@angular/core';
import { Subscription }   from 'rxjs/Subscription';
import { ModalService } from './modal.service'

@Component({
  selector: 'my-modal',
  template: `
    <div class="modal-body">
    {{data}}
    {{content}}
    </div>
  `
})

export class ModalComponent implements OnDestroy {
  @Input() data: string;
  content = 'hello';

  subscription: Subscription;
  constructor(
    private modalService: ModalService
  ) {
    this.subscription = modalService.modal$.subscribe(
      content => {
        this.content = content;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Frameworks used include angular v2.1.0, angular-cli v1.0.0-beta.16, ng-bootstrap v1.0.0-alpha.8

Answer №1

Success! Here's the solution:

  • To implement in the component (where the modal is opened):

    const myModal = this.modalService.open(MyModalComponent);
    
    myModal.componentInstance.dataPassed = this.passedData;
    
    myModal.result.then(result => {
      // do something with the result
    }                                                       
    
  • In the modal component (receiving end):

    export class MyModalComponent { 
    
     dataPassed: dataType;     // declare it!
    
     someFunction() {     // or utilize a lifecycle hook 
      console.log(this.dataPassed)  // now you can use it!
     }
    
    // remainder of the MyModalComponent 
    }
    

Answer №3

Check out these methods for accomplishing it.

  • Create a representation of a module
  • Utilize resolve and present resolved values on a representation of NgbActiveModal
  • Employ resolve and connect resolved values to the inputs of the module.

For further details, visit: https://example.com/ng-bootstrap-solutions

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

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...

Preventing Bull Queue from automatically re-starting jobs upon server restart

Currently, I am utilizing the bull queue system for processing jobs. Imagine a scenario where a job is in progress with an active status and I restart my development server. Upon restarting the worker script, the job remains in the active state within the ...

Monitoring and recording the current line number during evaluation

Recently, I've been experimenting with eval to modify a $scope object named variables. This is the watcher I'm using: $scope.$watch(function () { return $scope.variables; }, function (variables) { console.log('changed!'); }, true) ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

NextJS-created calendar does not begin on the correct day

I'm facing an issue with my calendar code where it starts rendering on a Wednesday instead of a Monday. I want to adjust the layout so that it always begins on a Monday by adding some empty boxes at the start of the calendar. Essentially, I need to s ...

Steps to eliminate the x icon from the text box that appears automatically in Internet Explorer

I'm currently working with a UI5 text box that includes a built-in option for clearing the text using a 'X' button. However, I've noticed that in Internet Explorer, an additional default cross mark is being added alongside the UI5 cros ...

What are the best practices for utilizing createHash('sha1') effectively in node.js?

Exploring the intricacies of a login system using React, MySQL, and Node.JS has been an interesting journey. Here's a glimpse of what I've accomplished so far: Presenting my router setup: const express = require('express') const app = ...

Automatic Clicks in the Chrome Console

I've come across a website that requires me to click on multiple elements scattered throughout the page Here is the code for one of the elements: <span class="icon icon-arrow-2"></span> Is there a way to provide me with the console comm ...

Creating a custom Map type in TypeScript

I am exploring the concept of defining a Map type in Typescript using generics. Essentially, I want to create something similar to: EntityMap<U, V>, where U can only be either a string or a number This is what I have managed to come up with so far: ...

Getting rid of the empty spaces between the lines of cards in Bootstrap 4

I want to eliminate the vertical space between the cards in my layout. Essentially, I want the cards to maximize the available space. I am open to using a plugin if necessary, but I have not been able to find any relevant information online (maybe I used t ...

Retrieving 'this' within the catch clause following the execution of a promise

When using the this keyword within a catch clause after initiating a promise, it displays "this" as undefined. Here is my scenario: I have a service with a Router object injected into its constructor. From a method in the service, an HTTP request is made t ...

Assigning IDs to Values in Angular 2

Here is the code snippet in question: <select [(ngModel)]=""> <option value="1">New York</option> <option value="2"Phoenix</option> <option value="3">Boston</o ...

Initialization of Masonry JS occurs prior to images being fully loaded

I am in the process of creating a website to serve as my portfolio for university applications. Despite my efforts, I am struggling with the javascript aspect and have not been successful in resolving the issue by following similar inquiries. The problem ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

Reverse the text alteration when the user leaves the field without confirming

Upon exiting a text box, I aim to display a confirmation dialogue inquiring whether the user is certain about making a change. If they select no, I would prefer for the text box to revert back to its original state. Is there an uncomplicated method to ach ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Learn how to retrieve data from a parent component in Angular 8 by leveraging the window.opener property in a child window

On my Angular application, I have 2 separate pages - page1 and page2. Page1 has a button that, when clicked, opens page2. Since they are different components, I need to use window.opener to access data from page1 in page2 by calling window.opener.page1Func ...

Endless cycle of NGRX dispatching

I tried creating a simple ngrx project to test the store, but I encountered an infinite loop issue. Even after attempting to mimic other examples that do not have this problem. To begin with, I defined 2 class models as shown below: export interface IBookR ...

Get the jsonarray file using express, node, and angular by downloading it

Within my web application, I am generating jsonarray files. These files have a structure similar to this: [{attr1:"123",attr2:"456"},{attr1:"abc",attr2:"def"}] I need to send these jsonarray files to the client for ...

Unable to retrieve nested objects from HTTP Response

After receiving data from a HTTP Response, I am trying to access and display it in my template. However, despite storing the data into a component variable, I am encountering issues when trying to access specific properties of the object. { "files": [ ], ...