Dynamically load components within a modal window

I am looking for a way to dynamically load a custom component inside a modal while keeping it as flexible as possible.

Here is an example :

-HTML CODE-

<button id="floating_button" class="floating_button animation_floating_in" (click)="loadCustomComponent('new_post_form_modal')"><i class="material-icons">gesture</i></button>
      <div class="modal-content" id="loadHere" >
          <!-- CUSTOM COMPONENT WILL BE LOADED HERE  -->
      </div>

-TYPE SCRIPT CODE-

public loadCustomComponent(componentName:any)
{
    // Dynamically load componentName inside the div with id="loadHere"
}

Any assistance with this would be greatly appreciated. Thank you!

Answer №1

Creating dynamic components can be achieved as shown in the example below:

   @Component({
     selector: "parent",
     template: `<button id="floating_button" class="floating_button animation_floating_in" (click)="createNewPost('new_post_form_modal')"><i class="material-icons">gesture</i></button>
  <div class="modal-content" #loadHere > ;
      <!-- LOAD MY CUSTOM COMPONENT HERE  -->
  </div>`
   })
   export class ParentComponent {
      @ViewChild("loadHere", { read: ViewContainerRef }) childContainer: ViewContainerRef;

    constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {}

    createNewPost = (componentName): void => {
       componentToLoad = 'resolve component here using componentName'; 
       this._cr.resolveComponent(componentToLoad ).then(cmpFactory => {               
          this.childContainer.createComponent(cmpFactory);
       });
     }
   }

If passing parameters is needed, you can refer to this resource

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

Turning off @Output as Observable: A step-by-step guide

I have a query regarding unsubscribing Outputs in Angular. While I am aware that EventEmitter is automatically cleaned up, there was a time when I needed to use an Observable as my Output. Specifically, I wanted to take an Output that emitted events at mos ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Issue with Typescript express application utilizing express-openid-connect wherein cookies are not being retained, resulting in an infinite loop of redirects

For a while now, I've been facing a block with no resolution in sight for this particular issue. Hopefully, someone out there can lend a hand. Background I have a TS express application running on Firebase functions. Additionally, I utilize a custom ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

What causes the variation in Http Post Response between the Console and Network response tab?

Currently, I am tackling an issue in angular2 related to HTTP post response. The problem arises when my endpoint is expected to return a boolean value. Interestingly, the response appears correctly in Chrome's Network response tab; however, upon loggi ...

Is it possible for Angular version 15 to function without needing to migrate to material

Can anyone clarify whether material migration is necessary when upgrading from Angular v14 to v15? The Angular upgrade guide mentions that old(v14) material modules can still be used by utilizing legacy modules, so is it mandatory to migrate? "In the new ...

Is it possible for me to create a union type that connects parameters and responses in a cohesive manner

I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type. For instance, consider the following scenario: type ResponseMap = { requestPath: ...

Troubleshooting: Authentication guard not functioning properly in Angular 2 due to HTTP request

As I work on implementing a guard for certain routes in my application, I face an issue. To grant access to the route, my intention is to send an HTTP request to my express backend API and check if the user's session exists. I have explored various e ...

The Ionic 5 app features a white iframe that functions perfectly on the web platform

Whenever I run my web application's function, the iframe is displayed. However, on Android, all I see is a white screen. Can anyone assist with resolving this issue? HMTL html <ion-content> <ion-button expand="full" color="warning" (clic ...

Exploring Partial Views in Bootstrap Single Page View and AngularJS

Currently, I am utilizing Bootstrap's single page view design, specifically the one found at this link: http://www.bootply.com/85746. As my code in the view has grown to nearly 500 lines and is expected to expand further, I am seeking a method to crea ...

Is there a way to omit type arguments in TypeScript when they are not needed?

Here is a function I am currently working with: function progress<T>(data: JsonApiQueryData<T>): number { const { links, meta } = data.getMeta(); if (!links.next) { return 1; } const url = new URL(links.next); return parseInt(url ...

Upon initializing an Angular project from the ground up, I encountered an issue where a custom pipe I had created was not

After creating an Angular 16.1.0 application and a custom pipe, I encountered error messages during compilation. Here are the steps I took: Ran ng new exampleProject Generated a pipe using ng generate pipe power Modified the content of app.compone ...

What is the best way to preserve an enumeration value in TypeScript?

Is there a way to save enumeration values in TypeScript? For instance: createArticle(name: string, clr: ??enumeration??) { return axios.post(`${environment.apiUrl}/cards`, { card: `${name}`, color: ??clr?? }, ... } PS: Conte ...

When applying animations to ngIf, the elements end up overlapping

I'm struggling to animate div elements when toggled using the Angular directive *ngIf. The issue I'm facing seems to be a common delay/timing problem in animations, but I haven't been able to find a solid solution. 1) When the current elem ...

What could be causing the error message "why can't shows read property

Within my Ionic-Angular application, I have successfully loaded the content from the database and printed it on the console. However, I am facing an issue where I cannot bind this content to the view. The error message that appears is displayed in https:// ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

Utilizing Angular's async pipe to dynamically customize and assign values to variables

I have a parent component named A with over 20 child components, all of which extend A and are located within <ng-content></ng-content>. Within component A, I am updating the value of the showContent variable in multiple places. The issue aris ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...

Encountering an Unknown Error when attempting to retrieve a response using Angular's httpClient with

The Service.ts file contains the following code: public welcome(token: any){ let tokenString = "Bearer "+token console.log("tokenString is: "+tokenString) let header = new HttpHeaders().set("Authorization",tokenSt ...