Prime Vyapar

Tales from a Developer's Trenches

Programmatically rendering components - Angular

Programmatically rendering components - Angular - Prime Vyapar
In addition to using a component directly in a template, you can also dynamically render components. There are two main ways to dynamically render a component: in a template with NgComponentOutlet, or in your TypeScript code with ViewContainerRef. On this page Using NgComponentOutlet Using ViewContainerRef Lazy-loading components

Using NgComponentOutlet

NgComponentOutlet is a structural directive that dynamically renders a given component in a template.

Code Snippet
Copy
                
                   
<ng-container *ngComponentOutlet="getCustomComponent()" />


Code Snippet
Copy
                
                   
getCustomComponent() { return this.isAdmin ? AdminBio : StandardBio; //Assuming here we have proper variable/property declaration/component }

Using ViewContainerRef

While ViewContainerRef interacts with the DOM, it's not directly represented in HTML code itself. It's an Angular service that acts behind the scenes.

Code Snippet
Copy
                
                   
<div> <ng-container #myContainer></ng-container> </div>


Code Snippet
Copy
                
                   
import { Component, ViewChild, ViewContainerRef } from '@angular/core'; @Component({ selector: 'app-my-component', template:
}) export class MyComponent { @ViewChild('myContainer', { read: ViewContainerRef }) container: ViewContainerRef; // Example: Dynamically create and insert a new component createComponent() { const component = this.container.createComponent(SomeComponent); } }

In this example, the @ng-container> with #myContainer acts as the placeholder. The component class injects ViewContainerRef using @ViewChild and assigns it to the container property. This allows the component to interact with the DOM container and dynamically add components like SomeComponent using createComponent.
Here's how ViewContainerRef interacts with your component's template:
  1. Template Placeholder: In your HTML template, you define a placeholder element (often <ng-container>) to mark the location where you want to dynamically insert components.
  2. Component Class Interaction: Within your component class, you use @ViewChild to get a reference to this placeholder element and access the associated ViewContainerRef instance.
  3. Dynamic Component Management: Using the ViewContainerRef methods (e.g., createComponent), you can dynamically create and insert new components into the container at runtime.

Leave a Comment

This sample demonstrates the full features of Rich Text Editor that includes all the tools and functionalities.

Comments