Incorporating user input into the dynamic creation process of an Angular 2 component using ComponentResolver

After successfully loading a dynamic Angular 2 component using ComponentResolver and ViewContainerRef, I am faced with the challenge of passing input variables from the parent component to the child component.

parent.ts

@Component({
 selector: "parent",
 template: "<div #childContainer ></div>"
})
export class ParentComponent {
 @ViewChild("childContainer", { read: ViewContainerRef }) childContainer: ViewContainerRef;

 constructor(private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {}

 loadChild = (): void => {
      this._cr.resolveComponent(Child1Component).then(cmpFactory => {               
         this.childContainer.createComponent(cmpFactory);
      });
 }
}

child1

@Component({
 selector: "child1",
 template: "<div>{{var1}}</div><button (click)='closeMenu()'>Close</button>"
 })
 export class Child1Component {
    @Input() var1: string;
    @Output() close: EventEmitter<any> = new EventEmitter<any>();

    constructor() {}

    closeMenu = (): void => {
      this.close.emit("");
    }
 }

In the scenario described above where loadChild is triggered by a button click, the challenge remains on how to effectively pass the value of var1 as an input into the child component. Additionally, subscription to the close EventEmitter decorated with @Output needs to be implemented.

Answer №1


To implement this, you must pass it imperatively like:

loadChildren(): void {
  this._cr.resolveComponent(Child1Component).then(cmpFactory => {               
    let cmpRef = this.childrenContainer.createComponent(cmpFactory);
     cmpRef.instance.var2 = anotherValue;  
   });
 }

Similar approach is needed when registering handlers for outputs.

loadChildren(): void {
  this._cr.resolveComponent(Child1Component).then(cmpFactory => {                
    let instance: any = this.childrenContainer.createComponent(cmpFactory).instance;
    if (!!instance.open) {
      // open is eventemitter decorated with @output 
      instance.open.subscribe(this.open);
    }
  });
}

open = (): void => {
  // perform necessary actions..
  this.childrenContainer.clear();
}

Answer №2

This is the approach I took using Angular 2.2.3

let elementNode = document.getElementById("test");
let factoryComponent = this.componentFactoryResolver.resolveComponentFactory(AnyCustomComponent);
let newComponent = factoryComponent.create(this.viewContainerRef.injector, null, elementNode);
// Here is where you set the @Input value
newComponent.instance.anyInput = anyValue;

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

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...

How to Utilize Output() and EventEmitter() for Value Transmission in Angular Application

Last week I was successfully able to implement Output() and EventEmitter() in my Angular app. However, today I am facing a new challenge while trying to apply the same concept in a different scenario. I'm not sure what I might be overlooking. Firstly ...

Can Firestore be debugged effectively?

In developing my application, I've been utilizing Angular and Firestore. However, I've encountered a challenge when it comes to ensuring the security of my app, as most CRUD tutorials I come across do not address the specific rules needed for Fir ...

Encountering a deadly mistake with LNK1181 while attempting to npm install web3

On my Windows system, I attempted to install the web3 node package using npm install. I followed the necessary steps by first installing Windows build tools: npm install --global --production windows-build-tools This command executed without issues, but ...

What is the best approach for determining which CSS file to import in next.js?

I'm currently facing the task of selecting which CSS file to apply in my next.js project. I have two separate CSS files, one for desktop and one for mobile devices. My current method of importing CSS files is as follows: // _app.tsx import ".. ...

Attempting to create a sorting functionality using Vue and Typescript

I am trying to implement a feature where clicking on the TableHead should toggle between sorting by most stock on top and least stock on top. Currently, I have two buttons for this functionality, but it's not very user-friendly. My approach involves ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

What is the best way to retrieve an item from an array?

I have an array containing multiple records and I need to extract just one record from it using its id as an object. However, the result I'm getting is an array with that single record. Is there a way to resolve this issue? Result: [{…}] 0: {id ...

Unable to retrieve npm repository from GitHub

I've been grappling for approximately 2 hours to integrate a repository into my angular project without success. Here's the link I've been trying: https://github.com/cmelange/ECL-3D-Components#ecl-3d-components. Despite previously having i ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Change the color of certain rows in the table

I'm currently working on a project using Angular4 and ngx-datatable, so my .html file looks like this: <ngx-datatable> <ngx-datatable-column> <ng-template> ... {{row.value}} My goal is to check the value of eac ...

Tips for resolving the issue of 'defineExpose' method being undefined in Vue3

Struggling to pass a method from child to parent; unfortunately, the defineExpose() method seems to be malfunctioning. Could anyone provide guidance on what might be going wrong? For additional context, feel free to check out my previous question <scri ...

Adding conditional props to a style object in @emotion/react with Typescript is as simple as utilizing a ternary operator

https://i.sstatic.net/KWrCP.png Can someone help me understand how to use props to control my CSS in emotion? ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

Gulp is failing to create a JavaScript file from TypeScript

Below is the Gulp task I am using: var gulp = require('gulp'); var typescript = require('gulp-typescript'); var sourcemaps = require('gulp-sourcemaps'); var tsProject = typescript.createProject('tsconfig.json'); var ...

Issues with Cognito integration in setting up a Cloudfront Distribution for hosting static content on S3

I've been facing an issue with my S3 website behind a CloudFront distribution when trying to authenticate with Cognito. Everything works perfectly when testing my Angular app locally with Callback URL and Sign out URL set to localhost:4200/. https:// ...

The callback type in TypeScript is used to define the types

I have encountered this scenario: function createCar(name: string, callback: () => void) function buildEngine(name: string): Engine function createCarWithEngine(carName: string, engineName: string, callback: (param: Engine) => void) { let created ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

Contrast two observables that exhibit varying structures

I currently have two observables linked to Firebase using AngularFire and RxJS. private boatsCollection: AngularFirestoreCollection<Boat>; boats: Observable<Boat[]>; private bookingsCollection: AngularFirestoreCollection<Booking>; bookin ...

Implementing Form Validation in Angular 5 and showing errors in a reusable component

My current setup includes a generic component structured as follows: // selector: 'app-text-box' <form> <input type="text" [name]="data.name" [id]="data.name"/> </form> <error-message [message]="message"></ ...