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

What is the best way to split a single object into two separate objects based on a specific value within the object using lodash?

Imagine a scenario with an object containing two channels in Dutch (NL) language and one channel in English (EN) language: [ { "name": "De Redactie", "channels": [ { "name": "headlines", "pub ...

Errors in TypeScript Compiler for using react-bootstrap in SPFx project

After setting up an SPFX Project with Yeoman generator and including react-bootstrap as a dependency, I encountered errors when using react-bootstrap components and running gulp serve. The error messages are as follows; does anyone have any solutions to ...

How can I bypass additional ngIf checks in the Angular template if a variable is null?

I have this code snippet in my template: <div class="icon-action" *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual" (click)="delete(node)"> ...

Methods for adding a new object to an array in Angular: Explained

How can I insert a new object in Angular? Here is the current data: data = [ { title: 'Book1' }, { title: 'Book2' }, { title: 'Book3' }, { title: 'Book4' } ] I would like to update the obje ...

Encountered a problem while attempting to build with ng build --prod. No issues when using ng serve or excluding

My project was working smoothly with ng build --prod until I decided to update the TypeScript version from 2.72 to 2.92 in my package.json file. Now, after the update, an error message pops up: ERROR in Cannot read property 'Symbol(Symbol.iterator ...

The Angular application has been successfully deployed on a Tomcat server as a war

I am planning to deploy a single page application (SPA) developed in Angular, along with various static files like *.css, .js, /assets/, all packed inside a war file on Tomcat. The issue I am facing is that whenever a user enters a path that does not corr ...

Learn the process of seamlessly uploading various document formats, videos, and previewing documents with Angular software

I am having trouble viewing uploaded files in the carousel. While I can see video and image files, other document formats are not displaying. Can someone please recommend a solution to enable viewing all types of documents as well? mydata = [] onSelect ...

Encountering Error TS2411 when upgrading from Typescript version 1.0.0 to 1.1.0-1

After updating my TypeScript using npm install typescript -g, I have been encountering a recurring error during compilation. Although the compilation is successful, it's becoming tedious. cmd.exe /D /C C:/Users/Vado/AppData/Roaming/npm/tsc.cmd --sour ...

Unable to resolve all parameters for the RouterUtilities class

My goal is to develop a RouterUtilities class that extends Angular's Router. Despite the app running and compiling smoothly, when I run ng build --prod, it throws an error message like this: ERROR in : Can't resolve all parameters for RouterUtil ...

Modifying pagination page box color in Angular material

Can anyone provide instructions on how to customize the color of the pagination drop down menu? View example image here ...

Tips for showing the upcoming week in an angular application

Could someone please assist me with displaying the dates for the next 7 days using TypeScript? I am familiar with obtaining the date for the 7th day ahead, but I am unsure on how to generate a list of the 7 consecutive days. ...

Tips on how to modify the session type in session callback within Next-auth while utilizing Typescript

With my typescript setup, my file named [...next-auth].tsx is structured as follows: import NextAuth, { Awaitable, Session, User } from "next-auth"; // import GithubProvider from "next-auth/providers/github"; import GoogleProvider from ...

Enums are not recognized by TypeScript when used within an array

I have defined an enum as follows: export enum Roles { ADMIN, NONE; } An object is being used which utilizes this enum. The structure of the object is: export interface User { name: string; roles: Roles[]; } Upon fetching this object via a web r ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Issue with Angular 5 template: "AbstractControl type does not contain property 'length'"

While attempting to compile my Angular project using the command ng build --prod --output-path <my_destination_path>, I encountered a few errors like the following: ERROR in src/app/products/product-edit/product-edit.component.html(190,10): : Proper ...

What steps can be taken to avoid special characters in ion-input fields?

When inputting special characters into the field used for storing the alphanumeric serial number, they are accepted. I need to prevent special characters from being entered in the input field. <ion-input [(ngModel)]="serial_number" (ngModelCha ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

Tips for incorporating the observer design pattern in REST APIs (Communication between front-end and back-end)

Is it possible to subscribe once to an API and receive multiple responses until I unsubscribe from that event? If so, how can this be achieved? If not, why does this approach not align with the observer pattern's guidelines? I attempted using the yie ...

Utilizing Laravel 5.5 and Angular on a Subdomain

Currently, I am facing a challenge in setting up a small project that involves Laravel and Angular. My goal is to have the Laravel 5.5 backend running on domain.com while the Angular frontend is hosted on app.domain.com. I attempted to install Angular wi ...