What are some alternatives to dynamicComponentLoader in Angular 2 RC5?

I am currently developing an Angular 2 app in RC5 where I need to dynamically load Components.

In the past, in RC1, I achieved this by using dynamicComponentLoader as shown below:

@Component({
  moduleId: module.id,
  selector: 'generic-component',
  templateUrl: 'generic.component.html',
  styleUrls: ['generic.component.css']
})
export class GenericComponent implements OnInit {
  @ViewChild('target',{read:ViewContainerRef}) target; 
  @Input('component-name') componentName:string;
  @Input('component-info') componentInfo:string;
  @Input('component-model') componentModel:Object;

  keysRegister:string[]=[     
  'users',
  'employee'
  ]; 
  componentNames:string[]=[      
  'UserComponent',
  'EmpComponent'
  ];

  constructor(private dcl:DynamicComponentLoader) {}

  ngOnInit() {
  }

  ngAfterViewInit(){
      let componentIndex=this.keysRegister.indexOf(this.componentName);
      this.dcl.loadNextToLocation(StandardLib[this.componentNames[componentIndex]],this.target)
    .then(ref=>{
        ref.instance.componentModel=this.componentModel;
    });
    console.log("GenericComponent...... "+this.componentName+" Loaded");

  }

}

Whenever I needed to load the component, I simply did the following:

<div *ngIf="columnModel" style="border:1px solid orange">
    <generic-component 
        [component-name]="columnModel.componentName" <!-- Here I would pass *users* -->
        [component-model]="columnModel.componentModel"
        [component-info]="columnModel.componentInfo"
    ></generic-component>
</div>

I attempted using componentResolver but encountered issues getting it to work properly. Any suggestions or guidance would be greatly appreciated. Thank you.

Answer №1

If you're working with RC5, the compileComponentAsync() method from the Compiler is essential.

For example, here's how you can implement it:

constructor(private _comp: Compiler) {}

ngAfterViewInit(): void {
    this._comp.compileComponentAsync(this.componentModel).then(a => this.target.createComponent(a));
}

You can also find a comprehensive example in one of my libraries:

https://github.com/flauc/ng2-simple-components/blob/master/src/modal/modal.component.ts

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

Finding the Height of a Document in Angular 2

I'm currently in the process of transitioning some jQuery code to Angular 2, and am facing difficulties in finding a way to retrieve the height of the document. The jQuery code I've been using is $(document).height(); Could you please provide ...

The function Promise.all typically yields an array with nested arrays

Inside my node Router, the following code snippet is implemented: router.get("/single-base/:id", (req, res) => { Base.find({ _id: req.params.id }) .then(bases => { let basefetches = []; for (let base of bases) { ...

The circular reference error message "Redux Action 'Type alias 'Action' circularly references itself" appears

I am currently working with two different actions: export const addToCart = (id: string, qty: number) => async ( dispatch: Dispatch, getState: () => RootState ) => { const { data }: { data: IProduct } = await axios.get(`/api/products/${id}`) ...

Ways to resolve issues with v-model rendering errors

I currently have code fragments within my index.blade.php file that look like this: The content section: . . . <div class="col-12 col-md-12 mb-3"> <label for="attachment" text-muted">Attachment</label> &l ...

Leveraging Angular directives for shared functionality

I am faced with the challenge of multiple components sharing common logic, and I am looking for a way to centralize this logic in one file to avoid duplicating code in each component. One solution that comes to mind is using a directive. Do you think this ...

What is the process for integrating Chart.js type definition into your project?

Utilizing a chart component for generating new charts: import { AfterViewInit, Component, ElementRef, Input, ViewChild } from '@angular/core'; import Chart, { ChartConfiguration } from 'chart.js/auto'; @Component({ selector: ' ...

Adding JSON information into a .js file using ajax technology

I am currently working on integrating a calendar template into my system. In the demo JavaScript file, example events are structured like this: events: [ { id: 1, title: 'Title 1', start: ('2016-01-02'), ...

Utilize Selenium's explicit wait feature to wait until a group of buttons on a web page become clickable

On a webpage, there is a collection of buttons. Each button has the same source code except for the link text. I am looking to verify that all the buttons on the page are clickable using WebDriverWait.until. Currently, I can confirm the clickability of th ...

Easily include Access-Control-Allow-Origin: * in JSON data

My web server hosts a folder (let's say the link is: www.foo.com/json/). Within this directory, there is a json file named foo.json. I am interested in accessing this file from a different website. I attempted to research "CORS," but found it to be q ...

What might be causing the lack of JSON updates appearing on my webpage?

I am facing an issue with my JSON file. After making updates to the file, the changes are not reflected on my webpage. Even after refreshing multiple times, only the old data is being displayed. I am using xampp local server and ajax for retrieving the JSO ...

Limit the use of the angular directive to only one instance

Hey there, I'm currently working with a directive that captures global events like mousedown, mouseup, and scroll on the body tag. I'm interested to know if there's a way to restrict the usage of an angular directive so it can only be used o ...

Updating the textarea with Ajax without the need for a button click or refreshing the

I need to implement a feature where a textarea will automatically update the database without requiring the user to click on any buttons or refresh the page. The idea is that after a keyup event, there should be a 2-second countdown timer. If no additional ...

The possibility exists that the onClick function may be null

I am encountering an issue with a props function that is showing an error message stating that the object may be null. import {Dropdown} from "react-bootstrap"; interface GenreButtonProps { key: number; id: number | null; genre: strin ...

Is there a way to extract array images from a database using an API, convert it into a JSON array, and display it in a HTML Angular

I am trying to retrieve option images from my database using an API, and then I want to add the image values to a JSON array so I can display them on an HTML page. The structure of my database is as follows. I have attempted various methods to retrieve th ...

Load pages seamlessly with AJAX

I'm facing a challenge: Is there a way to dynamically refresh a <div> element on a webpage using AJAX, without displaying loading bars and without causing the existing content to disappear while new content is being loaded? I would like the pr ...

Leverage the power of ExpressJS by seamlessly sharing route middleware between routes

Looking for a way to share multiple route middleware across various routes and controllers? Check out this setup: In app.js, we require ./routes/index.js: // load fs module var fs = require('fs'); // import routing files module.exports = func ...

Give an npm package a nickname using a browserify shim

I'm in the process of transitioning from requirejs to browserify. One of the dependencies I have is for masonry. Trying to shim it using the bower version was proving to be a little challenging (more on that can be found here). Instead, I decided t ...

Displaying elements upon clicking using Javascript

I am in the process of achieving this task without Jquery. My goal is to display a div when triggering an event. Currently, I have the following code to hide the element: document.getElementById('element').style.display = 'none'; Her ...

Creating fixed values in HTML

I need to maintain consistency in the headings of multiple tables spread across 3 HTML pages. The heading structure is as follows: <thead> <tr> <th>MyHeading</th> </tr> </thead> My goal is to store the string MyHeadin ...

How can a parent component update a child component's prop value in VUE?

I'm facing an issue with managing dynamic props in Vue with TypeScript. Below is my parent component: <script setup lang="ts"> const friends = [ { id: "emanuel", name: "Emanuella e", phone: "08788 ...