Dynamically generating an Angular component and populating it with data

I am currently working with Angular 7/8 and I have some code that adds a new component dynamically. In the parent component, my .ts file includes the following:

PARENT COMPONENT

Within the .ts file:

  @ViewChild(InjectDirective) injectComp: InjectDirective;

  constructor (private componentFactoryResolver: ComponentFactoryResolver) {}


  addComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    viewContainerRef.createComponent(componentFactory);
  }

And in the .html file:

<button (click)="addComponent()">Add Component</button>

Additionally, there is a custom directive implemented:

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

@Directive({
  selector: '[appInject]'
})
export class InjectDirective {

  constructor(public viewContainerRef: ViewContainerRef) {}

}

Lastly, we have the child component:

CHILD COMPONENT:

Inside the child component, the following code exists:

  export class ChildComponent implements OnInit {

  @ViewChild('viewer') private viewer: ElementRef;

}

In the HTML template of the child component:

<div>I AM A COMPONENT</div>

The goal is to pass unique data to each newly created child component.

How can I achieve this?

Answer â„–1

Utilize the instance property found in the ComponentRef that is returned when calling

viewContainerRef.createComponent(componentFactory);

  addComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const compRef = viewContainerRef.createComponent(componentFactory);
    compRef.instance.someProperty = "some data";
  }

Check out a live demo here!

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 ng test is not successful due to a SassError that indicates the stylesheet import cannot be found

I am facing an issue with my .scss files in my Angular project. Everything works fine when I build for development or production, but when I run tests using ng test, I encounter errors like: SassError: SassError: Can't find stylesheet to import. 1 â” ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

Testing the integration of socket.io with Angular through unit tests

Currently, I am in the process of unit testing an angular service within my application that is responsible for creating a socket.io client. The structure of my service can be seen below: export class SocketService { private name: string; private host ...

Angular - Dismiss modal triggered by service, from a header module

Within my Angular application, I have Service S that is responsible for opening Component C MatDialog; I am aiming for C to include a reusable header component called Component H; My goal is for H to feature a button that can close the MatDialog within C; ...

What is the best way to approach writing a shared value that is utilized across multiple files in Angular?

I am currently implementing Angular for the front end of my project. One challenge I'm facing is managing a single value, such as a 'role id', that needs to be used in multiple .ts files within Angular. Can anyone suggest an efficient way ...

Guide to integrating and utilizing a personalized JavaScript file within TypeScript components in an Angular 2 application

I have created a standard Angular 2 App using angular-cli. Now, I am trying to incorporate a custom .js file into it. Here is a simplified version of what the file looks like: 'use strict'; var testingThing = testingThing || {}; testingThing. ...

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

What is preventing me from setting the User object to null in my Angular application?

Currently, I am working on a project in Angular and encountering a specific issue. In my service class, the structure looks like this: export class AuthService { authchange: new Subject<boolean>(); private user: User; registerUser(authD ...

Extracting the content within Angular component tags

I'm looking for a way to extract the content from within my component call. Is there a method to achieve this? <my-component>get what is here inside in my-component</my-component> <my-select [list]="LMObjects" [multiple]=&qu ...

What could be the possible reason for the token having a null value during login authentication in

As a beginner to Angular, I am facing an issue with my JWT login page implementation. Despite printing the token in the console and confirming its existence as a string, I am receiving a null (or undefined) value. This is the code snippet from my UserServi ...

Tips for working with Typescript: utilizing the default value for a non-existent computed property

When utilizing Computed Property in javascript, I can structure my code as follows const default_values = {a:"debug",b:"info",c:"warning"}; function execute(y) { let x = default_values[y] || default_values.a /* if y is no ...

Tips on mocking an ngrx selector within a component

Within a component, we utilize an ngrx selector to access various segments of the state. public isListLoading$ = this.store.select(fromStore.getLoading); public users$ = this.store.select(fromStore.getUsers); The fromStore.method is formed using the ngrx ...

Utilizing a React npm component within an Angular project: A step-by-step guide

After successfully creating a simple react component and publishing it to the NPM registry, I encountered an issue when trying to use the same plugin in an Angular project. The custom plugin can be found at: https://www.npmjs.com/package/reactcustomplugin ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...

Guide on Applying a Dynamic Color in VueJs 3 Composition API/Vuetify Using CSS

Currently, my project utilizes Vue 3 with the composition API and Vuetify for the UI. I am looking to utilize a color that is already defined in a Vuetify theme variable within my CSS, similar to how I have done it previously in JavaScript. Although I at ...

Ensuring the accurate usage of key-value pairs in a returned object through type-checking

After generating a type definition for possible response bodies, I am looking to create a function that returns objects shaped as { code, body }, which are validated against the typing provided. My current solution looks like this: type Codes<Bodies> ...

"Exploring the power of D3, TypeScript, and Angular 2

I am facing challenges incorporating D3 v4 with Angular 2 (Typescript). While exploring D3 v4, I have referred to several solutions on StackOverflow without success. I have imported most of the necessary D3 libraries and typings (utilizing TS 2.0) and adde ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...