DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Rediscovering Angular: Modern Advantages and Technical Stack

Trending

  • Why Database Migrations Take Months and How to Speed Them Up
  • How to Perform Custom Error Handling With ANTLR
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Dynamically Create a Component in Angular

How to Dynamically Create a Component in Angular

Follow along with this interesting tutorial to learn how you can dynamically create and load a component in your web app using the Angular framework.

By 
Dhananjay Kumar user avatar
Dhananjay Kumar
·
Feb. 08, 18 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
180.9K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will learn to create a component dynamically. You may need to load a component dynamically in various scenarios, such as wanting to show a popup modal.

Let us assume that we have a component as listed below, which we will load dynamically.

import { Component, Input } from '@angular/core';

@Component({
    selector: 'app-message',
    template: `<h2>{{message}}</h2>
`
})
export class MessageComponent {
    @Input() message: string;
}

To load MessageComponent dynamically you need a container. Let us say that we want to load MessageComponent inside AppComponent. We need a container element in the AppComponent.

The template for AppComponent is as below:

<div style="text-align:center">
     <h1>
         Welcome to {{ title }}!
     </h1>
     <template #messagecontainer>
     </template>
 </div>

As you can see, we have an entry point template or a container template in which we will load MessageComponent dynamically.

In AppComponent, we need to import the following:

  1.  ViewChild, ViewContainerRef, and ComponentFactoryResolver from @angular/core. 
  2.  ComponentRef and ComponentFactory from @angular/core. 
  3.  MessageComponent from message.component.

After importing the required elements, AppComponent will look like the following code block:

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentFactoryResolver,
    ComponentRef,
    ComponentFactory
} from '@angular/core';
import { MessageComponent } from './message.component';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    title = 'app';
}

We can access template using ViewChild inside the Component class. The template is a container in which we want to load the component dynamically. Therefore, we have to access template with ViewConatinerRef.

ViewContainerRef represents a container where one or more views can be attached. This can contain two types of views.

Host Views are created by instantiating a component using createComponent and Embedded Views are created by instantiating an Embedded Template usingcreateEmbeddedView. We will use Host Views to dynamically load MessageComponent.

Let us create a variable called entry which will refer to the template element. In addition, we have injected ComponentFactoryResolver services to the component class, which will be needed to dynamically load the component.

export class AppComponent {
    title = 'app';
    @ViewChild('messagecontainer', { read: ViewContainerRef }) entry: ViewContainerRef;
    constructor(private resolver: ComponentFactoryResolver) { }
}

Keep in mind that the entryvariable, which is a reference to a template element, has an API to create components, destroy components, etc.

To create a component, let us first create a function. Inside the function, we need to perform the following tasks:

  • Clear the container.
  • Create a factory for MessageComponent.
  • Create a component using the factory.
  • Pass the value for @Input properties using a component reference instance method.

Putting everything together, the createComponent function will look like the below code:

createComponent(message) {
    this.entry.clear();
    const factory = this.resolver.resolveComponentFactory(MessageComponent);
    const componentRef = this.entry.createComponent(factory);
    componentRef.instance.message = message;
}

We can call the createComponent function on click event attached to the button. Let us put two buttons in the template and call the createComponent function when a button is clicked.

In the output, you can see that component is getting loaded dynamically on the click of the button.

As you click on the buttons, the component will be reloaded with a different message. You can destroy a component using the destroy method on the componentRef.

destroyComponent() {
    this.componentRef.destroy();
}

You can either destroy a dynamically loaded component by manually calling the function or by putting it inside the ngOnDestroy() lifecycle hook of the component so that when the host component is destroyed, the dynamically loaded component will also be destroyed.

Putting everything together, AppComponent will look like the code below:

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentFactoryResolver,
    ComponentRef,
    ComponentFactory
} from '@angular/core';
import { MessageComponent } from './message.component';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    title = 'app';
    componentRef: any;

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

    createComponent(message) {
        this.entry.clear();
        const factory = this.resolver.resolveComponentFactory(MessageComponent);
        this.componentRef = this.entry.createComponent(factory);
        this.componentRef.instance.message = message;
    }
    destroyComponent() {
        this.componentRef.destroy();
    }
}

At this point, when running the application, you will get an error because we have not set the entryComponents in AppModule. We can set that as shown in the listing below:

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

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

This is all you need to do to load a component dynamically in Angular.

Template AngularJS

Published at DZone with permission of Dhananjay Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Recursive Angular Rendering of a Deeply Nested Travel Gallery
  • 50+ Top Angular Interview Questions and Answers
  • Automated Bug Fixing: From Templates to AI Agents
  • Rediscovering Angular: Modern Advantages and Technical Stack

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!