Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4?

This is the Chooser Component

import {InputComponent} from './input/input.component'
import {BlockComponent} from './block/block.component'

export const FormChooser = {
  Block: BlockComponent,
  Input: InputComponent
}

Here we have the Component Builder

const selectedComponent = FormChooser[data.component]
const componentFactory = this.Resolver.resolveComponentFactory(selectedComponent)

const newlyCreatedComponent = this.ViewContainerRef.createComponent(componentFactory)

Trying to access the ViewContainerRef of new_component? So you can implement code like this

const anotherNewComponent = newlyCreatedComponent.createComponent(componentFactory) // as ViewContainerRef

Thanks in advance...

Answer №1

You have the option to either include ViewContainer in the constructor of a dynamic component:

class CustomComponent {
  constructor(public vcRef: ViewContainerRef) {}
}

const factory = this.Resolver.resolveComponentFactory(CustomComponent)

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef; 

or utilize @ViewChild to obtain a reference to ViewContainerRef:

 template: '<ng-container #ref></ng-container>'
})
class CustomComponent {
  @ViewChild('ref') vcRef: ViewContainerRef;
}

const factory = this.Resolver.resolveComponentFactory(CustomComponent )

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef; 

Answer №2

Incorporating Angular +8

import { InputNumberComponent } from '../input-number/input-number.component';
@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  styleUrls: ['./dynamic-form.component.scss']
})
export class DynamicFormComponent implements OnInit {

  @ViewChild('ref', { read: ViewContainerRef }) vcRef: ViewContainerRef;
  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
    const dynamicComponent = this.resolver.resolveComponentFactory(InputNumberComponent)
    this.vcRef.createComponent(dynamicComponent)
  }

}

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 ngx-translate Angular translation file is being loaded twice unnecessarily

Upon reviewing the network tab in the browser's developer tools, I discovered that my Angular app translation file is being loaded twice. Is there an issue with this? Should it be loading multiple times? https://i.stack.imgur.com/vcKm1.png ...

Tips for utilizing an elective conversion by typing

In my opinion, utilizing code is the most effective approach to articulate my intentions: interface Input { in: string } interface Output { out: string } function doStuff(input: Input): Output { return { out: input.in }; } function f<Out>(input ...

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

NextJs Route Groups are causing issues as they do not properly exclude themselves from the app's layout.tsx

As far as I know, the layout.tsx in the app directory serves as the root layout. To customize the layout structure for specific segments, you can use Route Groups. More information can be found here. In this setup, any page.tsx file inside a directory nam ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

Is Typescript generating error TS2411 within its own Typescript module?

After transitioning to using @types in Typescript 2.0, I executed npm i -S typescript @types/typescript to ensure everything was set up correctly with typescript. However, whenever I run tsc on my project and exclude "node_modules", I encounter the same e ...

Introducing an extra 'pipe' in rxjs angular may result in generating errors

Encountering an unusual issue with Angular. The following code functions correctly: this.form.valueChanges .pipe( startWith(this.form.value), pairwise(), tap(() => console.log('aa')) ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

Create a custom validation function that accepts additional parameters

At the moment, I have implemented the following code but I haven't utilized the extra data yet. create-room.component.ts import { Component, Inject, OnInit } from '@angular/core'; import { AbstractControl, FormBuilder, FormControl, FormGroup ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

When setting up Webpack with TypeScript, an error is encountered related to imports

Recently, I attempted to convert my Webpack configuration from JavaScript to TypeScript but encountered numerous difficulties in the process. To kick things off, I created a basic webpack configuration file with some parts missing. Here is how my webpack.c ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

The Angular2 Router directs the user to the main Component

After configuring the Angular2 router and setting up the server (asp.net core) to redirect unknown paths to /index.html, the routing appears to be functioning properly. However, I am encountering an issue where visiting a specific URL (i.e. www.sitename.co ...

When using EmotionJS with TypeScript, the theme type is not properly passed to props when using styled components

CustomEmotions.d.ts import '@emotion/react'; declare module '@emotion/react' { export interface Theme { colors: { primaryColor: string; accentColor: string; }; } } MainApp.tsx import { ...

What is the method for nesting data within a component's child>child>child structure?

In the structure I am working with, there is a hierarchy: Root component buttons (menu search component) - an input field for searching Widgets (widget component ) (Cats widget) - displays what is input in the menu search here. My challen ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Using constant variables as arguments in functions in TypeScript

While learning about TypeScript, I encountered some confusion regarding how it handles const variables. Let's consider a scenario where I define an interface for a number: interface MyNumber { value: number; } If I then create a constant MyNumbe ...

The issue of process.server being undefined in Nuxt.js modules is causing compatibility problems

I've been troubleshooting an issue with a Nuxt.js module that should add a plugin only if process.server is true, but for some reason it's not working as expected. I attempted to debug the problem by logging process.server using a typescript modu ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...