Add a component to another component in real-time

Check out my StackBlitz demo: DEMO

I'm attempting to insert the 'table' component into the #test section of the app component when the visualization type is 'table'. To achieve this, I am using the createTable() function which generates and inserts <app-table> tags within the #test div.

The <app-table> tag exists in the DOM but the content of table.component.html is not displayed (the table doesn't show up!) This may be due to it being just a tag and not a compiled component.

Is there a way to have the content of the table component appear inside the app component?

Answer №1

Give this a shot!

 buildTable() {
    this.wrapper.clear(); 
    const compFactory = this.resolver.resolveComponentFactory(DataTableComponent);
    this.compReference = this.wrapper.createComponent(compFactory);  

  }

Your Modified Example:https://stackblitz.com/edit/dashboard-inchara-9s6lfd

Answer №2

To dynamically add components, utilize the ComponentFactoryResolver. Detailed information can be found in the Angular Docs. Check out a complete solution on stackblitz: ComponentFactoryResolver. Here's a summary of what was implemented:

For table creation in app.component.ts:

createTable(container) {
  let componentFactory = this.componentFactoryResolver.resolveComponentFactory(TableComponent);
  let viewContainerRef = this.insTable.viewContainerRef;
  viewContainerRef.clear();
  let componentRef = viewContainerRef.createComponent(componentFactory);
}

The anchor point directive used: table.directive.ts:

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ins-table]',
})
export class TableDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

In app.component.html:

<div #charts id="test">
  <ng-template ins-table></ng-template>
</div>

Also, don't forget to set up app.module.ts with the necessary declarations for everything to function correctly:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular-highcharts';

import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';
import { TableComponent } from './table/table.component';
import { TableDirective } from './table/table.directive';

@NgModule({
  imports: [BrowserModule, ChartModule, HttpClientModule],
  declarations: [AppComponent, TableComponent, TableDirective],
  bootstrap: [AppComponent],
  providers: [HttpClientModule],
  entryComponents: [
    TableComponent
  ]
})
export class AppModule { }

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

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Adjust the variable value if the "for" loop encounters an error

In my situation, I have a spreadsheet that contains a script responsible for checking another linked spreadsheet for a customer's name and then returning the associated code. Everything works smoothly when the customer name is found in the "CustomerCo ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Performing a reverse image search request using Javascript/AJAX to query Google

I have been attempting to perform a reverse image search request using AJAX, but I keep receiving 302 errors. After checking the Firebug console, I discovered that the response header from Google contains a URL linking me to the results. However, I am unsu ...

Utilizing Parent Scope Variables in AngularJS Directives with Isolated Scopes

I'm feeling a bit lost here (edit: after clarification, my question is "Why isn't the directive recognizing the attributes passed to it?"), even though I thought I had a good grasp on it. I'm having trouble accessing the properties of the pa ...

Building a multilingual website using AngularJS UI-Router

I am currently working on developing a multilingual website using AngularJS. While providing translations in templates seems straightforward, I am facing challenges when it comes to implementing proper multilingual routes using UI-Router. Unfortunately, I ...

Is there a way to identify the source of a div's scrolling behavior?

While working on a complex web page that involves multiple JQuery Dialogs and other widgets, I encountered a frustrating issue. Some of the dialogs contain divs with scrolling abilities (using overflow-y with a fixed height). Whenever I click on one dialog ...

Strange issue: the code appears to be running multiple times with just one click

I've implemented a commenting system with a like feature. However, I'm facing an issue where sometimes clicking the like link results in sending multiple requests (up to 8-9) per click. This problem also occurs with another jQuery code that is tr ...

Tips for invoking the setState method via an onClick event the ES6 way

class BlogPost extends React.Component{ //getInitialState constructor(){ super(); this.onLike = this.onLike.bind(this); this.state = { like :0 } } onLike(){ this.setState({ li ...

Issue with Rails 5 Bootstrap 3 Modal and Ajax functionality not functioning as expected

In the process of developing an app in Rails 5 and utilizing Bootstrap 3 as the framework. A custom user controller has been set up to enable admins create, edit, and delete users. Modals are being implemented for the user creation form, where the modal i ...

What is the reason for all the buttons activating the same component instead of triggering separate components for each button?

I am facing an issue with my parent component that has 3 buttons and 3 children components. Each button is supposed to open a specific child component, but currently all the buttons are opening the same child component when clicked. The children components ...

Issue: [ng:areq] The function 'DepartmentCustomReportController' is missing and undefined in Internet Explorer

I am encountering an issue specifically in Internet Explorer, as the same controller works without any problems in Chrome. Here is a snippet of my index.html file: <script src="assets/js/boostrapJs/jquery-1.11.1.min.js"></script> <script s ...

Discover the method to retrieve the month name from an HTML Date input value

Here we have a date input field <input id="customer-date" name="customer-date" type="date" required> Accompanied by this script const customerDate = document.getElementById('customer-date').value; const dateHandler = document.getElementB ...

What could be causing my inability to accurately guess people's ages?

My latest project involves developing a game where players have to guess names from images. Each game consists of 10 rounds, followed by a bonus round where participants must wager their points on guessing the age of the person in the image within a 2-year ...

What is the best way to retrieve a variable within a nested function?

I'm struggling to access a variable from within a nested function in the following code: $(function() { var key = getRandomKey(dictionary); resetInputRow(dictionary[key]); $("#button").click( function() { var answer = key; ...

Is it possible to overlook TypeScript errors when compiling with Angular 2 AoT?

My application is experiencing numerous TypeScript errors, even though it runs correctly. I recently migrated a JavaScript app to TypeScript and am struggling to resolve all the type-related issues. In order to proceed with development, I have configured m ...

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Is there a more effective approach to managing an array of objects retrieved from an API call?

I'm attempting to extract an array of names from a JSON response that contains an array of objects, but I'm running into issues. When I try to print the array, it shows up empty. Is this the correct way to go about it? There don't seem to be ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...