Invoke function using ngComponentOutlet

Can anyone help me figure out how to dynamically call a method of a component using ngComponentOutlet?

Here's an example code snippet from my Caller:

this.dialog.open(FormDialogComponent, {data: {body: ChildComponent}});

In the FormDialogComponent:

export interface FormDialogData {
    title: string,
    body: Type<any>
}

export class FormDialogComponent {
    @ViewChild(ChildComponent) child!: ChildComponent;
    constructor(public dialogRef: MatDialogRef<FormDialogComponent>, @Inject(MAT_DIALOG_DATA) public data: FormDialogData) {}
    save(){
        this.child.save(); // trying to call save() method of childComponent but it's not working
    }
}

Any ideas on how I can successfully call the save method of my child component?

ADD

Oh, I forgot to include the html part:

<ng-container [ngComponentOutlet]="data.body" #child></ng-container>

Answer №1

After some troubleshooting, I was able to resolve the issue

The caller remains the same

within My formDialogComponent.ts file

@ViewChild('formComponent', {read: ViewContainerRef}) viewContainerRef!: ViewContainerRef;

Furthermore, in formDialogComponent.ts

// Instantiating my component
this.childComponent = this.viewContainerRef.createComponent(this.data.body).instance;

located in formDialogComponent.html

<button mat-raised-button color="primary" (click)="childComponent.save()"><mat-icon>add</mat-icon></button>

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

When adding new elements to an array, the IDs of all objects become identical

When running the code below: dietDay.meals.forEach((meal) => { meal.mealProducts.forEach((mealProduct) => { if ( mealProduct.product.id && this.fetchedProductIds.includes(mealProduct.p ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

What about combining a fat arrow function with a nested decorator?

Trying to implement a fat arrow function with a nestjs decorator in a controller. Can it be done in the following way : @Controller() export class AppController { @Get() findAll = (): string => 'This is coming from a fat arrow !'; } Wh ...

Validating emails using angular material chips

I'm currently working on implementing a form that utilizes input chips to facilitate sending messages to multiple email addresses. While I've made progress in making the form functional, I'm facing difficulties in displaying error messages w ...

Leveraging Angular Universal: Retrieve Store within Guard on the server-side with the help of NgRx

I am currently working on an Angular 9 Universal application that utilizes NgRx for managing state. Additionally, I have integrated ngrx-store-localstorage to save the Store data in the user's localStorage. My main challenge lies in verifying whether ...

Is there a way to prevent the URL of my Next.js app from constantly changing?

Our current Next.js project requires that the static URL remains constant, even when navigating between pages. This is a client requirement that we must adhere to. Can you provide suggestions on how we can achieve this? Maintaining the same URL throughout ...

Dynamic placeholder modification depending on form selection

How can I dynamically change the placeholder text based on user selection? //div with a toggle for two options <div fd-form-item> <label fd-form-label for="select-targetType">Showroom type:</label> <select class=&q ...

steps for retrieving final outcome from forkJoin

I am currently working with an array of userIds, such as: ['jd', 'abc']. My goal is to loop through these userIds and retrieve full names using an API. Ultimately, I aim to transform the initial array into [ {userId: 'jd', nam ...

Steps for Creating a User in the Meetup API

Exploring the functionalities of the meetup API has sparked my interest in incorporating it within my application to facilitate user creation, group joining, event hosting, and more. I am uncertain about the feasibility of this endeavor. Situation Imagi ...

Guide to sending back an Observable within Angular 4

Inside my authProvider provider class, I have the following method: retrieveUser() { return this.afAuth.authState.subscribe(user => { return user; }); } I am looking to subscribe to this method in a different class. Here is an example ...

Develop a professional Angular application for deployment

Help! I'm struggling to build my Angular application for production. After running the 'ng build --prod' command, I can't find all my components in the 'dist' folder. Do I need to change or configure something else? I see som ...

Exploring Angular 2 on Apache: A Guide to Optimizing for Search Engine

After creating a basic Angular 2 app and hosting it on an Apache server, I'm unsure if search engines will crawl my site. I read that the site must be rendered server side but couldn't find more information about it online. ...

How to disable the first option in an Angular 2 select dropdown

I'm working with a select component, and here is the code snippet I have: <select name="typeSelection" materialize="material_select" [(ngModel)]="trainingplan.type" > <option [ngValue] = "null" disabled selected>Please choose a ...

The function you are trying to call is not valid... the specified type does not have any call signatures [ts 2349

Having some trouble using functions from Observable Plot example with a marimekko chart in my TypeScript project. I encountered an error on this particular line: setXz(I.map((i) => sum.get(X[i]))) The code snippet causing the issue is as follows: fu ...

Is the return type determined by the parameter type?

I need to create an interface that can handle different types of parameters from a third-party library, which will determine the return type. The return types could also be complex types or basic types like void or null. Here is a simple example demonstra ...

What is the reason behind continuously receiving the error message stating "Not all code paths return a value here"?

Can someone help me understand why I am consistently encountering this error message from typescript? PS. I am aware that in this scenario I could simply use a boolean and not create a function, but my focus here is on typescript. I keep receiving the er ...

Concealed Dropdown Option

<div fxFlex="25" fxFlex.xs="100" class="px-8"> <div class="form-label">Reporting Status <span class="reqSgnColor">*</span> </div> <mat-form-field appearance=&quo ...

Assigning the output of a function to an Angular2 component (written in TypeScript)

I have a small utility that receives notifications from a web socket. Whenever the fillThemSomehow() method is called, it fetches and stores them in an array. @Injectable() export class WebsocketNotificationHandler { notifications: Array<Notificati ...

Sortable layouts and tables in Ionic 3

I found a great example of an Ionic table that I'm using as reference: https://codepen.io/anon/pen/pjzKMZ <ion-content> <div class="row header"> <div class="col">Utility Company Name</div> <div c ...

Verify user using Cognito user pool log-in information

Is it possible to authenticate a user using only user pool credentials without an identity pool/IdentityPoolId? Check out this link for more information: https://github.com/aws/amazon-cognito-identity-js The example provided in the link above specifically ...