Dynamically load a custom element with a Component

I am attempting to dynamically inject a component into a container.

Component:

@Component({...})
export class InvestmentProcess{

    @ViewChild('container') container;
    constructor(public dcl: DynamicComponentLoader) {}

    loadComponent(fooComponent: Type){
        this.dcl.loadNextToLocation(fooComponent, container);
    }
}

Template:

<div #container> </div>

Upon running the loadComponent function, an error is thrown:

TypeError: location.createComponent is not a function

This is because the variable container is of type ElementRef, while loadNextToLocation expects a ViewContainerRef as the second parameter. According to the official documentation, the ViewContainerRef can be obtained from an element using @ViewChild, but I have not found a proper example to do so.

Working with Angular2.0.0rc1

Answer №1

DynamicComponentLoader is on its way to becoming obsolete. It is recommended to use

ViewContainerRef.createComponent()
instead.

@Component({...})
export class InvestmentProcess{

    @ViewChild('container', {read: ViewContainerRef}) container:ViewContainerRef;
    constructor(private resolver: ComponentResolver) {}

    loadComponent(fooComponent: Type){
      this.resolver.resolveComponent(fooComponent).then((factory:ComponentFactory<any>) => {
        this.cmpRef = this.target.createComponent(factory)
      });        
    }
}

For more information, please visit Angular 2 dynamic tabs with user-click chosen components

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

The QueryParams/ParamMap consistently returns as blank

Seeking assistance with retrieving a parameter called serverId from the URL. I have the following code setup: constructor(private peopleService: PeopleService, private route: ActivatedRoute) { this.route.paramMap.subscribe(params => { ...

How can I change an icon and switch themes using onClick in react js?

I have successfully implemented an icon click feature to change the colorscheme of my website (in line 21 and changeTheme). However, I also want the icon to toggle between FaRegMoon and FaRegSun when clicked (switching from FaRegMoon to FaRegSun and vice v ...

Execute a function at a designated time without having to open the application

Currently in the process of developing a .NET Core application with Angular and Ignite UI. I was wondering if there is a way to execute a function in the background without requiring the webpage to be open. For instance, would it be feasible to automatica ...

I need to confirm the permissions of the token that I receive from AAD when using microsoft-ada-angular6 and microsoft-graph-client

Currently, I am implementing the Implicit Grant workflow in Angular utilizing the microsoft-adal-angular6 library to authenticate users within my application and then acquire a token for accessing the Microsoft Graph. Fortunately, the authentication proce ...

Angular 7 ESRI loader search widget focus out bug: finding a solution

I am currently working on implementing an ESRI map using esri-loader in my Angular application. Everything seems to be working fine, but I am encountering an error when typing something into the search widget and then focusing out of it. "Uncaught Typ ...

What is the best way to implement multiple templates for a single component?

Is there a way to configure my Home Component based on the user's role? For instance: If the employee is an admin, then the home component should load the template URL designed for admins. Likewise, if the employee is a cashier, then the home compo ...

Is there a way to run the mediapipe face detection codepen.io demo on my laptop?

After successfully running the mediapipe face detection demo from Mediapipe official website, I wanted to replicate it on my laptop. To achieve this, I created an 'index.html' file and meticulously transferred the code from the CodePen demo page ...

Using jest-dom without Jest is definitely an interesting challenge that many developers may

Can anyone help me with extending Typescript interfaces? I have come across a situation that I am trying to solve. In my tests, I am utilizing expect without using Jest directly (I installed it separately and it functions properly). Now, I am interested ...

Problem Encountered in Angular 4 CLI when using enableProdMode in Internet Explorer 11

Currently, my Angular 4 application built using NodeJS works flawlessly on Internet Explorer 11 and the latest versions of Chrome and Firefox during development. However, when I enable Production Mode in the NodeJS Build as shown in the example from packa ...

Can a TypeScript generator function be accurately typed with additional functionality?

Generator functions come with prototype properties that allow for the addition of behavior. The generated generators inherit this behavior. Unfortunately, TypeScript does not seem to recognize this feature, leaving me unsure of how to make it aware. For i ...

Determine the type of function arguments based on provided hints in TypeScript

It's common to encounter situations like this where TypeScript struggles to infer types due to lack of context. Is there a way to explicitly declare the type of function for the compiler? router.get('/get', imget); router.get('/send&a ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

How can we design a return type for a function in Typescript that enforces the exact keys present in the input array K[] to be included in the Record?

I have a function that takes an array of Animals, and returns a map where the keys are the animals and the values are their fur colors: export enum Animals { CAT = 'CAT', DOG = 'DOG', SEAL_PUP = 'SEAL_PUP', } const furC ...

What is the method for deducing the names that have been announced in a related array attribute

In my definitions, I have identified two distinct groups: Tabs and Sections. A section is encompassed by tabs (tabs contain sections). When defining sections, I want the tab names to be automatically populated by the previously declared sibling tabs. But ...

Getting the readonly-item type from an array in TypeScript: A step-by-step guide

Is it possible to create a readonly item array from a constant array? const const basicValueTypes = [{ value: 'number', label: 'Number' },{ value: 'boolean', label: 'Boolean' }]; type ReadonlyItemArray = ??? ...

Proceed the flow of event propagation using the react-aria button element

In the react-aria library, event bubbling for buttons is disabled. I am facing an issue where my button, which is nested inside a div that acts as a file uploader, does not trigger the file explorer when clicked due to event bubbling being disabled. How ...

Arranging an array of objects by their alphanumeric string property values

Currently, I am facing an issue with sorting an array of objects in TypeScript. The structure of my array is as follows: [ { "title": "Picture3.jpg", "targetRange": "B2", "type": ...

Angular's queryParams do not appear to properly connect with the query parameters

My code seems to have a mistake somewhere, but I can't figure it out. In my [queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}", the params object is empty when I subscribe to it in the edit-server component. Why is it empty and how do I a ...

What ways can I dynamically implement styles using ngStyle in Angular?

Is there a way to toggle the position value from left to right based on a boolean condition? I am looking to switch [ngStyle]="{ 'left.px': offSetX } with [ngStyle]="{ 'right.px': offSetX } depending on a certain condition import { C ...

What is the best approach to obtain complete and error methods from the server using BehaviorSubject?

Here is a description of my unique service: @Injectable() export class SettingService { private settings = new BehaviorSubject<any[]>([]); constructor(private http: HttpClient) { this.loadSettings(); } private loadSettings( ...