Accessing Component Instance in Ionic 3 Modal Controller

I am currently displaying a Component called EventFeedbackComponent through ModalController. I want to subscribe to a Subject within the EventFeedbackComponent. How can I access the component instance in order to achieve this?

This is what my code looks like:

let modal   =   this.modalCtrl.create(EventFeedbackComponent);
modal.present();

// This code snippet is not functioning correctly and throws an error "ERROR TypeError: Cannot read property 'subscribe' of undefined"
modal._component.feedbackSubmit.subscribe(feedbackResponse => {
    console.log(feedbackResponse);
});

The documentation provided did not offer assistance in solving this issue: https://ionicframework.com/docs/api/components/modal/ModalController/

Here is the scenario where I need to implement this:

  • I have a list of Events in my Service that require feedback.
  • The EventFeedbackComponent contains features for gathering feedback on individual events.
  • I display the EventFeedbackComponent to collect feedback for the first event and listen for the event feedbackSubmit using a Subject.
  • Upon submission of the feedback, I display a Success Toast message and update my service variable to move on to the next event.
  • This process is repeated until feedback is obtained for all unreviewed events, utilizing the same Component displayed through a Modal.

Answer №1

Dismiss Modal with Parameters - Option 1

The Ionic modal component allows for closing dialogs with specific arguments:

modal.ts

constructor(public viewCtrl: ViewController) {
  this.prop = params.get('prop');
}

dismiss() {
  this.viewCtrl.dismiss({ test: '1' });
}

In the opener file, you should include:

opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.onDidDismiss(data => {
  alert('Closed with data:' + JSON.stringify(data));
});

If the above method is not sufficient, consider using:

Interact via ViewContainer.emit - Option 2

Utilize the ViewController::emit method to communicate data to the opener

modal.ts

constructor(public viewCtrl: ViewController) {}

sendFeedBack() {
  this.viewCtrl.emit({ someData: '2' });
}

opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.onDidDismiss(data => {
  alert('Closed with data:' + JSON.stringify(data));
});

modal.present().then(result => {
  modal.overlay['subscribe']((z) => {
    alert(JSON.stringify(z));
  })
});

Implement Input Callback - Option 3

Possibly pass a callback function as a parameter to the modal:

opener.ts

let modal = this.modalCtrl.create(TestComponent, { 
  'prop': 'prop1', 
  onFeedBack: (data) => {
    alert('Input callback' + JSON.stringify(data));
  }
});

modal.ts

onFeedBack: Function;

constructor(params: NavParams) {
  this.onFeedBack = params.get('onFeedBack');
}

sentThroughInputCallback() {
  this.onFeedBack({ s: '2' });
}

To receive the component instance, follow Option 4 below:

Access Component Instance - Option 4

You can only access the component instance after it has been created:

opener.ts

let modal = this.modalCtrl.create(TestComponent, { 'prop': 'prop1' });

modal.present().then(result => {
  const testComp = modal.overlay['instance'] as TestComponent;
  testComp.feedbackSubmit.subscribe(() => {
    alert(1);
  })
});

Explore further on Ng-run Example

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

Exploring the power of Angular 2 with Jasmine tests

Recently, I have been studying the guide on testing in Angular 2 using Jasmine as outlined in the tutorial found at https://angular.io/docs/ts/latest/guide/testing.html. Specifically, I have been working on incorporating Jasmine with Angular 2 by following ...

Is Angular 2 giving you trouble with the AoT compilation and module.id error?

I need to set up AoT compilation for my Angular 2 project. My application is organized into a js directory where all generated .js files are stored, and an app directory containing my .ts, .html, and .css files. For the AoT compilation process, I am usin ...

Is there a way to fetch a particular object from Firebase database based on its value using AngularFire2?

Here is the database I am working with: firebase database I am trying to retrieve a dish that has its 'featured' attribute set to true (dish.feature = true). Is it possible to do this directly from the database, or do I have to retrieve all di ...

Refreshing an Angular2 page is triggered by the update of a specific property

Just starting out with Angular2 and I'm puzzled as to why my page keeps refreshing when I try to set some properties from form data. Below is the component snippet: import { Component } from '@angular/core'; import { Credentials } from &ap ...

Tips for utilizing the "??=" syntax in Typescript

let x; x ??= 'abc' console.log(x); // abc Running the code above in the browser console does not cause any issues. However, when attempting to run it in TypeScript, an error is thrown. SyntaxError: Unexpected token '??=' Here is my c ...

Arrange chat participants based on the latest messages using React

Looking for a way to efficiently organize the array of users in my ReactJS chat application according to the latest and most recent messages they have sent, constantly updating with each new message, similar to WhatsApp or Telegram. Below are simplified s ...

Generate a unique Object URL for the video source by utilizing the binary string obtained from the backend

I've been facing an issue with loading binary video data from my backend using fastAPI. When I curl the endpoint and save the file, it plays perfectly fine on my laptop. For the frontend, I'm using React+Typescript. I fetch the binary video data ...

Using a Type Guard in Typescript to check if an environment variable matches a key in a JSON object

I am currently working on creating a Type Guard to prevent TypeScript from throwing an error on the final line, where I attempt to retrieve data based on a specific key. TypeScript is still identifying the environment variable as a string rather than a rec ...

Using template variable in Angular5 to create a dependant dropdown feature

I have a component where I am subscribing to an observable that contains nested levels of JSON objects. How can I create multiple dropdown selects that depend on the previous selection? I am using template variables to reference the selects. this._exposu ...

Tips for verifying the presence of a value within an array using checkboxes

My firestore database contains a collection named world with a sub-collection called languages I have developed two functions: one to retrieve all documents from the sub-collection languages, and another function to fetch every language if the userUid val ...

Adding Components Dynamically to Angular Parent Dashboard: A Step-by-Step Guide

I have a dynamic dashboard of cards that I created using the ng generate @angular/material:material-dashboard command. The cards in the dashboard are structured like this: <div class="grid-container"> <h1 class="mat-h1">Dashboard</h1> ...

What is the solution to the TypeScript error stating that there is no index signature with a parameter of type 'string' on the 'Object' type?

While working on an Angular project, I came across an issue when writing a Typescript function for a service. The error message stated: "Element implicitly has an 'any' type because expression of type 'string' can't be used to inde ...

Concealing the value of the variable within the state function

CODE USED: /*Code snippet from another page with specific URL*/ .state("main/handler/location/userSso",{ url:"/main/handler/:location/:", templateUrl:"component/common/main.html", controller: 'MainContro ...

Angular 5: Steps to send an event from authguard to header in Angular application

I am struggling to send out an event from the authguard component to the header component. Event broadcasting setup @Injectable() export class BroadcastService { public subject = new Subject<any>(); sendMessage(message: string) { this.subjec ...

Maximizing the potential of useRef within a function handler when utilizing hooks

I'm running into an issue where I am unable to set the state on values when submitting a form that sends an http request. It seems that the values are undefined and not being passed upon click, resulting in errors with the set...() function. Below yo ...

Encountering a hiccup while trying to install Svelte, Skeleton, and Tail

Recently entering the world of Svelte and TypeScript, I have encountered some unexpected errors after installation. Despite following the same steps as before, I am puzzled by what is causing these issues. This is the process I followed: npm create svelte ...

Eliminate the use of type assertion when verifying if a value is included in a union

I have a unique scenario where I am using a union type that involves an array. I need to check the values at run-time, but TypeScript is requiring me to use a type-assertion in this case. Take a look at the following code: const Pets = ["dog", &q ...

Utilizing Ace with a personalized theme in Angular 2 application while straying away from the default theme directory

I am currently facing an issue with integrating an Ace editor into my Angular 2 application, which is built using angular-cli. I want to link the Ace editor to a custom theme stored in the app's assets folder src/app/assets instead of within node_modu ...

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

The variable remains unchanged after the API call, despite using useState

Despite my efforts to find a solution, I still find myself puzzled by this question that has seemingly been answered before. The issue lies in the synchronization of my code when making a request to the what3words API. The data retrieved is assigned to a ...